diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..059d01a57f879d5d993d8041945baa29947f60c0 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/environment/workdir/sentence_sets.json @@ -0,0 +1,39 @@ +[ + { + "id": "SET01", + "source": "Sheet 5, question 10", + "sentences": [ + "M -> ~E", + "E -> M" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 13", + "sentences": [ + "~A & ~M", + "~M & ~E", + "A | E" + ] + }, + { + "id": "SET03", + "source": "Sheet 5, question 7", + "sentences": [ + "A | M", + "~E <-> A", + "E | A", + "~E" + ] + }, + { + "id": "SET04", + "source": "Sheet 2, question 3", + "sentences": [ + "~A", + "~M <-> A", + "~E & A", + "E | ~A" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/instruction.md b/tasks/argument-check/argument-check-consistency-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-e0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/task.toml b/tasks/argument-check/argument-check-consistency-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..813106dac6ee8640f05262c48b1b9d0d82f56102 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10000 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..dc4484b91d61f022cb3ec8bb43ae7c5cff884bf5 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/checks.json @@ -0,0 +1,110 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "M -> ~E", + "E -> M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "A | M", + "~E <-> A", + "E | A", + "~E" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.
. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-e0000/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..e1e1d523cd46d4740ca989bb241de8c9a7652266 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/environment/workdir/sentence_sets.json @@ -0,0 +1,37 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 13", + "sentences": [ + "~G", + "S & G" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 8", + "sentences": [ + "F <-> S", + "F", + "S <-> G", + "F & S" + ] + }, + { + "id": "SET03", + "source": "Sheet 7, question 20", + "sentences": [ + "~S", + "~F & S", + "~S & F" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 15", + "sentences": [ + "F -> ~G", + "~F & G" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/instruction.md b/tasks/argument-check/argument-check-consistency-d1-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-e0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-e0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/task.toml b/tasks/argument-check/argument-check-consistency-d1-e0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..650154a2db5c937b6d4b27abd3534d2f06b4b7f2 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10009 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d0fb66578e8cf452a2d65d0b98d09295262f3d35 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/checks.json @@ -0,0 +1,110 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "F <-> S", + "F", + "S <-> G", + "F & S" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "F -> ~G", + "~F & G" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-e0009/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..bb84b6a377ec76911cfdd1ea2161919b96a818e8 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/environment/workdir/sentence_sets.json @@ -0,0 +1,40 @@ +[ + { + "id": "SET01", + "source": "Sheet 6, question 16", + "sentences": [ + "L | E", + "E -> L", + "E <-> G", + "~L & ~G" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 4", + "sentences": [ + "~L -> G", + "G & L", + "G <-> L" + ] + }, + { + "id": "SET03", + "source": "Sheet 9, question 2", + "sentences": [ + "~L & ~E", + "~G | ~E", + "~G & E" + ] + }, + { + "id": "SET04", + "source": "Sheet 4, question 11", + "sentences": [ + "G", + "E", + "G | ~L", + "G <-> E" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/instruction.md b/tasks/argument-check/argument-check-consistency-d1-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-e0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/task.toml b/tasks/argument-check/argument-check-consistency-d1-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..226f1dcb9d4b0092e2e32a9e5b4c7e951bd59fe1 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10018 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5952f2b68791698ec954544a35ff941be5e41b0b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~L -> G", + "G & L", + "G <-> L" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "G", + "E", + "G | ~L", + "G <-> E" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-e0018/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-e0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..3033d368e3c9ed8c9b049803a8acc9c88a0ac851 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/environment/workdir/sentence_sets.json @@ -0,0 +1,37 @@ +[ + { + "id": "SET01", + "source": "Sheet 1, question 5", + "sentences": [ + "G -> A", + "L", + "L & ~A", + "~A & L" + ] + }, + { + "id": "SET02", + "source": "Sheet 4, question 9", + "sentences": [ + "L | ~G", + "G & ~L" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 16", + "sentences": [ + "L | A", + "~A & L", + "L <-> G" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 18", + "sentences": [ + "G -> ~L", + "L & G" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f7d5fb7eafa5d9361c5d0ed95dcbdb9b63bc35a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 0 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..af734201b5f573db980da0017811f6b2518cfe1e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "G -> A", + "L", + "L & ~A", + "~A & L" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "L | A", + "~A & L", + "L <-> G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0000/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..c9db09af6ff25ef9821ce313a6d19e58eb6d7e2a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/environment/workdir/sentence_sets.json @@ -0,0 +1,38 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 11", + "sentences": [ + "~E | B", + "B & E", + "~B | E" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 4", + "sentences": [ + "E & ~G", + "~E | ~G", + "E | G" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 17", + "sentences": [ + "B -> G", + "G <-> E", + "~E & G" + ] + }, + { + "id": "SET04", + "source": "Sheet 6, question 18", + "sentences": [ + "B & E", + "B -> ~E", + "E & B" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a19cc6c7c31e44c05bc8664e7e722355850b1d9a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 9 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..909e5e5b6c67f32b8837a276f8ef79b5b3dcb9f9 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/checks.json @@ -0,0 +1,110 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~E | B", + "B & E", + "~B | E" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "E & ~G", + "~E | ~G", + "E | G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0009/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..e476ad27cfc182ac469a0efaec63c4e0eb1fa885 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/environment/workdir/sentence_sets.json @@ -0,0 +1,36 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 5", + "sentences": [ + "N & A", + "~A | ~N" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 13", + "sentences": [ + "~N & ~A", + "M | ~N", + "~A -> ~M", + "~M & N" + ] + }, + { + "id": "SET03", + "source": "Sheet 2, question 10", + "sentences": [ + "~N -> M", + "~M -> ~N" + ] + }, + { + "id": "SET04", + "source": "Sheet 8, question 12", + "sentences": [ + "M -> A", + "A & ~M" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c7de44e777e3cb4d8beeb4b4c8091e1729f769c3 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 18 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f68042979a4e2afc44043e3477ee5d2ae059b844 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/checks.json @@ -0,0 +1,108 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~N -> M", + "~M -> ~N" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "M -> A", + "A & ~M" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0018/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..1b4d7e4df2eabb0f7f9b115e7fab123e969f4082 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/environment/workdir/sentence_sets.json @@ -0,0 +1,37 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 13", + "sentences": [ + "~E -> A", + "~C & ~E", + "C | E" + ] + }, + { + "id": "SET02", + "source": "Sheet 4, question 9", + "sentences": [ + "C & A", + "A -> C" + ] + }, + { + "id": "SET03", + "source": "Sheet 6, question 2", + "sentences": [ + "E & A", + "E -> A", + "A & ~E" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 4", + "sentences": [ + "~C | ~E", + "~C", + "~C -> ~E" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0027/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0027/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0027/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd015e606a120ad80f0f076b00b43130ad8ef1ba --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 27 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..322e6ad0912b9f865df3d6d5e4f19e14fd5c474e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/checks.json @@ -0,0 +1,109 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "C & A", + "A -> C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~C | ~E", + "~C", + "~C -> ~E" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0027/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0027/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..9d89abacf38c250df5a26db411392f5b2376aa1a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/environment/workdir/sentence_sets.json @@ -0,0 +1,39 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 14", + "sentences": [ + "A -> S", + "S & ~Q", + "~A & Q", + "~S & Q" + ] + }, + { + "id": "SET02", + "source": "Sheet 4, question 12", + "sentences": [ + "Q & ~S", + "~A & S", + "Q -> S", + "A | Q" + ] + }, + { + "id": "SET03", + "source": "Sheet 3, question 13", + "sentences": [ + "Q | A", + "Q & ~A", + "A -> Q" + ] + }, + { + "id": "SET04", + "source": "Sheet 4, question 11", + "sentences": [ + "Q | A", + "A <-> Q" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0036/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05f6c48c7483530ff7ab0d438d7408ef4dc465b5 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 36 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..989bbe32113d0b76786261c56d2dd5868f394039 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/checks.json @@ -0,0 +1,109 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "Q | A", + "Q & ~A", + "A -> Q" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "Q | A", + "A <-> Q" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0036/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0036/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..6609471b7ddb213a63b997849360c06949900cc8 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/environment/workdir/sentence_sets.json @@ -0,0 +1,37 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 7", + "sentences": [ + "G | L", + "Q & L", + "G | ~L" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 20", + "sentences": [ + "Q & ~L", + "L & Q" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 17", + "sentences": [ + "L | Q", + "~G <-> L", + "~Q -> G", + "L & G" + ] + }, + { + "id": "SET04", + "source": "Sheet 5, question 9", + "sentences": [ + "Q & ~L", + "Q | L" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0045/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1c74efab55cc09e076ab0e166fab862fdb28811 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 45 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..fcd14477f7322bc4025fd6ec28521a8925cefa26 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/checks.json @@ -0,0 +1,109 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "G | L", + "Q & L", + "G | ~L" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "Q & ~L", + "Q | L" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0045/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0045/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..7ae4ec304029a6f7947a6498088c3ece92cbd256 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/environment/workdir/sentence_sets.json @@ -0,0 +1,36 @@ +[ + { + "id": "SET01", + "source": "Sheet 7, question 15", + "sentences": [ + "D <-> B", + "D | ~B" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 8", + "sentences": [ + "~M & B", + "~M <-> B" + ] + }, + { + "id": "SET03", + "source": "Sheet 9, question 20", + "sentences": [ + "B & M", + "~B" + ] + }, + { + "id": "SET04", + "source": "Sheet 4, question 3", + "sentences": [ + "D | M", + "~D", + "~D -> B", + "D & M" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0054/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..acd141255f4e999595bc8e1d1ba2746cbabb5eb0 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 54 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0f5707b68a6f3ec8e7fbca0f6200b7b8e1bf54ee --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/checks.json @@ -0,0 +1,108 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "D <-> B", + "D | ~B" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~M & B", + "~M <-> B" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0054/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0054/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..3fc3c155ce081d5c458a1a1cd57c4ff41734fdfb --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/environment/workdir/sentence_sets.json @@ -0,0 +1,40 @@ +[ + { + "id": "SET01", + "source": "Sheet 1, question 5", + "sentences": [ + "D | M", + "D", + "~D & H", + "H -> D" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 15", + "sentences": [ + "~M <-> ~D", + "~M | ~H", + "~H & M" + ] + }, + { + "id": "SET03", + "source": "Sheet 2, question 7", + "sentences": [ + "M", + "M & ~H", + "H & D" + ] + }, + { + "id": "SET04", + "source": "Sheet 1, question 18", + "sentences": [ + "H <-> M", + "~M | H", + "M & D", + "H | M" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0063/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..65f66511b66efe9d8b497059f2c7b5ea7f325eb4 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 63 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f2593d63ac0e91b28b79f84437fd6fdea15a47f9 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~M <-> ~D", + "~M | ~H", + "~H & M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "H <-> M", + "~M | H", + "M & D", + "H | M" + ] + }, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0063/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0063/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..a4703eda80b8ca68e9ac7d11f084a337a8f23832 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/environment/workdir/sentence_sets.json @@ -0,0 +1,38 @@ +[ + { + "id": "SET01", + "source": "Sheet 8, question 14", + "sentences": [ + "K | ~P", + "~K -> P", + "P -> K" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 10", + "sentences": [ + "~K -> M", + "M <-> K", + "~P -> ~M" + ] + }, + { + "id": "SET03", + "source": "Sheet 2, question 7", + "sentences": [ + "K & ~P", + "~P <-> ~K", + "K & P" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 9", + "sentences": [ + "~P & ~M", + "P & ~M", + "P -> M" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0072/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2814d99df834e1c9be35091b1be95484a422d69 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 72 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f35b0283918a81f6ba3643a399e4a154edea9c73 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/checks.json @@ -0,0 +1,110 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "K | ~P", + "~K -> P", + "P -> K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~K -> M", + "M <-> K", + "~P -> ~M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0072/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0072/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..2315d413d3893eda976ddcfaa0fa1e9f8827da02 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/environment/workdir/sentence_sets.json @@ -0,0 +1,39 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 11", + "sentences": [ + "N & K", + "~N <-> K", + "K -> ~N" + ] + }, + { + "id": "SET02", + "source": "Sheet 1, question 8", + "sentences": [ + "N | K", + "Q | ~K", + "Q | ~N", + "Q -> K" + ] + }, + { + "id": "SET03", + "source": "Sheet 4, question 9", + "sentences": [ + "K & N", + "K -> N" + ] + }, + { + "id": "SET04", + "source": "Sheet 5, question 16", + "sentences": [ + "N & Q", + "Q & K", + "~K <-> Q", + "~K | Q" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/instruction.md b/tasks/argument-check/argument-check-consistency-d1-t0081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af76e976913e4be61ff0574cdfa0e80e71694782 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/instruction.md @@ -0,0 +1,14 @@ +# Argument check: consistency + +`sentence_sets.json` holds 4 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d1-t0081/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d1-t0081/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/task.toml b/tasks/argument-check/argument-check-consistency-d1-t0081/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cbc897f099da747b76818da2bd35d2c0b4d920b9 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 81 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/tests/checks.json b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8a296945689225f750b00df27d02e88eee4baf7d --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/checks.json @@ -0,0 +1,110 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "N | K", + "Q | ~K", + "Q | ~N", + "Q -> K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "K & N", + "K -> N" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/tests/test.sh b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/tests/validators.py b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d1-t0081/tests/verify.py b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d1-t0081/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..39f86847a64d90683735c5e2f2fadd66dfd072b3 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/environment/workdir/sentence_sets.json @@ -0,0 +1,64 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 6", + "sentences": [ + "~K & ~R", + "~J | ~R", + "J <-> G", + "K -> J", + "G & R" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 16", + "sentences": [ + "J | K", + "(J | ~G) & K", + "G -> K & J", + "J | R", + "G & (R | K)" + ] + }, + { + "id": "SET03", + "source": "Sheet 7, question 16", + "sentences": [ + "~J -> K", + "~G -> R", + "~R & G", + "~(G & ~J)", + "~(K & G)" + ] + }, + { + "id": "SET04", + "source": "Sheet 3, question 17", + "sentences": [ + "R | J", + "(~J -> ~K) | (J <-> R)", + "R & K", + "~J" + ] + }, + { + "id": "SET05", + "source": "Sheet 6, question 11", + "sentences": [ + "J | (R | G)", + "~G", + "~R -> ~G", + "J | G" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 10", + "sentences": [ + "G | J", + "~G & ~R", + "(R -> ~J) -> G" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/instruction.md b/tasks/argument-check/argument-check-consistency-d2-e0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-e0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-e0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/task.toml b/tasks/argument-check/argument-check-consistency-d2-e0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d3b655997f03f2dba91da3924b9e7a7cd52a5dc --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10003 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8061e287ca12bee085e4ddd2a611a5890180c7d4 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/checks.json @@ -0,0 +1,221 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "J | K", + "(J | ~G) & K", + "G -> K & J", + "J | R", + "G & (R | K)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "G", + "J", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~J -> K", + "~G -> R", + "~R & G", + "~(G & ~J)", + "~(K & G)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "G", + "J" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "K", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "J | (R | G)", + "~G", + "~R -> ~G", + "J | G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "J" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET04", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-e0003/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..aba56ee8e6e0bbf90c72155ddc68e8bc4285a4f9 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/environment/workdir/sentence_sets.json @@ -0,0 +1,62 @@ +[ + { + "id": "SET01", + "source": "Sheet 2, question 13", + "sentences": [ + "R & G", + "~G", + "(R | D) & (D & ~R)" + ] + }, + { + "id": "SET02", + "source": "Sheet 5, question 12", + "sentences": [ + "G", + "~N -> ~G", + "(N -> G) & (N -> D)" + ] + }, + { + "id": "SET03", + "source": "Sheet 6, question 6", + "sentences": [ + "~N -> ~G", + "D | G", + "(G <-> N) -> R & G", + "~D -> G & N", + "~G" + ] + }, + { + "id": "SET04", + "source": "Sheet 1, question 13", + "sentences": [ + "~R <-> G", + "G & ~N & (D <-> G)", + "~G", + "R | D & G", + "N <-> D" + ] + }, + { + "id": "SET05", + "source": "Sheet 5, question 8", + "sentences": [ + "~G & ~D", + "R", + "D & R -> N -> ~D", + "~(N | ~R)" + ] + }, + { + "id": "SET06", + "source": "Sheet 3, question 12", + "sentences": [ + "R -> N", + "(N <-> R) & (~R | N)", + "(~N <-> R) & (R | ~D)", + "~D" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/instruction.md b/tasks/argument-check/argument-check-consistency-d2-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-e0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/task.toml b/tasks/argument-check/argument-check-consistency-d2-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7dbbc96181911d1f22bf3832c23348207e74dbe4 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10012 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..011667f8e6a42da43c1aede0413cfca74c64e839 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/checks.json @@ -0,0 +1,220 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "G", + "~N -> ~G", + "(N -> G) & (N -> D)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "D", + "G", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~N -> ~G", + "D | G", + "(G <-> N) -> R & G", + "~D -> G & N", + "~G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "D", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "~G & ~D", + "R", + "D & R -> N -> ~D", + "~(N | ~R)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "D", + "G", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET04", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-e0012/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..0ffa53be845a6391b8ab0b6d3a4f77bb34abd31f --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/environment/workdir/sentence_sets.json @@ -0,0 +1,63 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 6", + "sentences": [ + "(Q -> R) & ~M", + "S | ~M", + "S & M", + "M | ~R", + "Q -> M" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 3", + "sentences": [ + "~R | ~Q", + "~R & ~Q", + "M | S", + "R | M -> ~R -> Q" + ] + }, + { + "id": "SET03", + "source": "Sheet 9, question 20", + "sentences": [ + "(~M -> ~R) | S", + "~Q", + "~S -> ~M", + "M" + ] + }, + { + "id": "SET04", + "source": "Sheet 8, question 2", + "sentences": [ + "~Q -> R", + "M | ~Q", + "~M <-> Q", + "R & ~Q" + ] + }, + { + "id": "SET05", + "source": "Sheet 5, question 13", + "sentences": [ + "~(M -> R)", + "R & ~S", + "Q <-> ~S", + "M | Q & ~R" + ] + }, + { + "id": "SET06", + "source": "Sheet 7, question 9", + "sentences": [ + "Q -> S", + "~Q & R", + "(~R <-> Q) -> ~S & R", + "S <-> R" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/instruction.md b/tasks/argument-check/argument-check-consistency-d2-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-e0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-e0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/task.toml b/tasks/argument-check/argument-check-consistency-d2-e0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..74fbb506901c23c9b81983319a29e512218dceed --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10021 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..98aa46c533f2a5273c54cdbfb3393cd67178ba57 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/checks.json @@ -0,0 +1,221 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~R | ~Q", + "~R & ~Q", + "M | S", + "R | M -> ~R -> Q" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "M", + "Q", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "(~M -> ~R) | S", + "~Q", + "~S -> ~M", + "M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "M", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~Q -> R", + "M | ~Q", + "~M <-> Q", + "R & ~Q" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "M", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET05", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-e0021/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-e0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..205558f84a2c52778b16a6a22e7abcad18a6f63e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/environment/workdir/sentence_sets.json @@ -0,0 +1,62 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 18", + "sentences": [ + "(D -> ~E) & ~K", + "K -> H", + "~E & ~K", + "H | K -> H & ~K", + "(~K <-> H) & (H | E)" + ] + }, + { + "id": "SET02", + "source": "Sheet 8, question 6", + "sentences": [ + "~D -> E", + "D <-> K", + "(~D | ~E) & K" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 6", + "sentences": [ + "E & ~D", + "~E", + "D -> H" + ] + }, + { + "id": "SET04", + "source": "Sheet 5, question 13", + "sentences": [ + "(H <-> E) & (~K | ~H)", + "H -> D", + "E | D", + "E <-> D" + ] + }, + { + "id": "SET05", + "source": "Sheet 4, question 17", + "sentences": [ + "E | ~H -> D", + "~E | H", + "D & K", + "~K & ~H", + "~K | (~D -> H)" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 11", + "sentences": [ + "~D <-> K -> ~H", + "~E", + "~H | D -> ~K", + "~D -> E" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..41a2ae6f8626543d4c4e09d2252ace4e76825cad --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 3 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..403fda126beb878bb4f2afc108f2fed93d44998b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/checks.json @@ -0,0 +1,221 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "(D -> ~E) & ~K", + "K -> H", + "~E & ~K", + "H | K -> H & ~K", + "(~K <-> H) & (H | E)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "H" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "E", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~D -> E", + "D <-> K", + "(~D | ~E) & K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "D", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "E" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "(H <-> E) & (~K | ~H)", + "H -> D", + "E | D", + "E <-> D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "D", + "E", + "H" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET05", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0003/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..3490559a9256a1353bc14560b9906e33cde893bc --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/environment/workdir/sentence_sets.json @@ -0,0 +1,63 @@ +[ + { + "id": "SET01", + "source": "Sheet 6, question 12", + "sentences": [ + "~S -> N -> ~F", + "S & ~N", + "~F & S", + "N | F" + ] + }, + { + "id": "SET02", + "source": "Sheet 5, question 13", + "sentences": [ + "F | C", + "S | F", + "~F", + "~C & ~S" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 19", + "sentences": [ + "~F", + "~C", + "~C | S", + "N -> ~S", + "(C -> S) & (C -> F)" + ] + }, + { + "id": "SET04", + "source": "Sheet 5, question 1", + "sentences": [ + "(S <-> N) & (S & N)", + "S & F", + "F -> ~C -> N", + "(C <-> S) -> S -> ~F" + ] + }, + { + "id": "SET05", + "source": "Sheet 5, question 13", + "sentences": [ + "F | ~N", + "S -> F & N", + "(F -> N) -> S -> N", + "~F & S" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 6", + "sentences": [ + "(C & ~S) | (~S | F)", + "S & F", + "C -> F", + "C <-> F" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d0830020402c74969f357f0a88dbb192d1b8c0f --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 12 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ed8024f94324277b34971f44a5555977f6c5b415 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/checks.json @@ -0,0 +1,219 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~F", + "~C", + "~C | S", + "N -> ~S", + "(C -> S) & (C -> F)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "C", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "(S <-> N) & (S & N)", + "S & F", + "F -> ~C -> N", + "(C <-> S) -> S -> ~F" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "F", + "N", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "C" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "(C & ~S) | (~S | F)", + "S & F", + "C -> F", + "C <-> F" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "C", + "F", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02", + "SET05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0012/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..806f67ded103951f757b6426252f6140c7af588b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/environment/workdir/sentence_sets.json @@ -0,0 +1,64 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 16", + "sentences": [ + "D & (~N | ~K)", + "N | R -> D", + "R <-> N", + "(N | R) & (R & N)", + "R & ~K" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 2", + "sentences": [ + "R -> K", + "N | R", + "~R & K & (~D | N)", + "~K", + "N | ~R <-> R <-> D" + ] + }, + { + "id": "SET03", + "source": "Sheet 9, question 7", + "sentences": [ + "~D", + "~N <-> (~D & R)", + "R -> ~N", + "~N <-> K" + ] + }, + { + "id": "SET04", + "source": "Sheet 7, question 14", + "sentences": [ + "~K | N", + "~(~K | ~D)", + "~N -> ~K" + ] + }, + { + "id": "SET05", + "source": "Sheet 3, question 7", + "sentences": [ + "D <-> ~K", + "~R", + "D | N", + "D & N <-> K", + "~K & N" + ] + }, + { + "id": "SET06", + "source": "Sheet 6, question 17", + "sentences": [ + "N | ~R <-> ~K", + "~K -> N", + "N <-> K", + "~R" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5049745a7bc8e5a448a1ccd52c0a3acdf63110a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 21 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c42760fc2953cd10c6efcf9b30a2f97b91942c09 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/checks.json @@ -0,0 +1,217 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "D & (~N | ~K)", + "N | R -> D", + "R <-> N", + "(N | R) & (R & N)", + "R & ~K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "D", + "N", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~D", + "~N <-> (~D & R)", + "R -> ~N", + "~N <-> K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "D" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~K | N", + "~(~K | ~D)", + "~N -> ~K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "D", + "K", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET05", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0021/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..1fff14b4349bcc1775081d8b7635676832f056df --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/environment/workdir/sentence_sets.json @@ -0,0 +1,63 @@ +[ + { + "id": "SET01", + "source": "Sheet 6, question 7", + "sentences": [ + "Q | ~D", + "~Q | N", + "Q <-> ~K -> ~D", + "D | Q", + "K & N" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 6", + "sentences": [ + "~Q", + "~(Q -> K)", + "~D -> K", + "~(~N & ~D)" + ] + }, + { + "id": "SET03", + "source": "Sheet 6, question 4", + "sentences": [ + "~D <-> Q", + "Q", + "K & ~Q", + "(D <-> K) & (Q | K)" + ] + }, + { + "id": "SET04", + "source": "Sheet 8, question 10", + "sentences": [ + "~Q", + "D & N", + "~D -> Q & K", + "N | K" + ] + }, + { + "id": "SET05", + "source": "Sheet 6, question 6", + "sentences": [ + "(~N -> D) -> (D <-> ~N)", + "N & ~Q", + "~N -> D" + ] + }, + { + "id": "SET06", + "source": "Sheet 5, question 5", + "sentences": [ + "Q & D", + "(Q <-> K) & (~Q | ~D)", + "K <-> Q", + "(N -> ~Q) <-> N & ~Q", + "K | N" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0030/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4037b469e1853b027d1faa2e91555438a4e7fa96 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 30 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2aa2de453d6879462f3cbd21d505bae537d3ff28 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/checks.json @@ -0,0 +1,219 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "Q | ~D", + "~Q | N", + "Q <-> ~K -> ~D", + "D | Q", + "K & N" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "K", + "N", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~Q", + "D & N", + "~D -> Q & K", + "N | K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "D", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "(~N -> D) -> (D <-> ~N)", + "N & ~Q", + "~N -> D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "D", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET03", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0030/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0030/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..94d6f80b298013bb7be471ea18e8ee8e13179f6f --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/environment/workdir/sentence_sets.json @@ -0,0 +1,60 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 18", + "sentences": [ + "~E | ~B", + "B & ~F", + "P | E", + "~(P & F)" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 16", + "sentences": [ + "B & E", + "F & B", + "F", + "F -> ~P" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 12", + "sentences": [ + "~B <-> F", + "F | (P | ~B)", + "~F & ~P" + ] + }, + { + "id": "SET04", + "source": "Sheet 8, question 6", + "sentences": [ + "E | ~B", + "B | E", + "~B & (P -> ~E)", + "E & B" + ] + }, + { + "id": "SET05", + "source": "Sheet 3, question 15", + "sentences": [ + "B & ~E", + "F & E", + "B -> E", + "E | F" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 5", + "sentences": [ + "~(E & ~F)", + "~E & F", + "~B -> ~F" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0039/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b0e54baf6984d90b39be01f26cee16ccc70b668b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 39 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..db7d87f733a11ff8065efab765b2e205048c0190 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/checks.json @@ -0,0 +1,221 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~E | ~B", + "B & ~F", + "P | E", + "~(P & F)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "B", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "E", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "B & E", + "F & B", + "F", + "F -> ~P" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "B", + "E", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "~(E & ~F)", + "~E & F", + "~B -> ~F" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "B", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "E" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04", + "SET05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0039/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0039/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..d323fab08b9730b431f855ab67b5dbb72ec0cf81 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/environment/workdir/sentence_sets.json @@ -0,0 +1,63 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 11", + "sentences": [ + "~M -> ~B", + "H & M & (H | B)", + "B | M", + "(~M & B) | ~H" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 16", + "sentences": [ + "~(B | H)", + "B -> ~H", + "~S | ~B", + "~H & B -> S" + ] + }, + { + "id": "SET03", + "source": "Sheet 7, question 20", + "sentences": [ + "H & M", + "B | ~S -> M | H", + "S | H", + "S -> H", + "H <-> B" + ] + }, + { + "id": "SET04", + "source": "Sheet 2, question 20", + "sentences": [ + "B -> ~S", + "(H -> B) & (S -> M)", + "B -> S", + "B | H" + ] + }, + { + "id": "SET05", + "source": "Sheet 9, question 8", + "sentences": [ + "~H", + "H <-> ~B", + "M & ~H", + "(B | H) & (M -> H)" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 17", + "sentences": [ + "M <-> H", + "H <-> ~B | M", + "~M | ~H", + "~S <-> ~H" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0048/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4a2d0c42f3742ec4924754c67516ec076ef26ddd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 48 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..efe9271f6aa0749717737514f09f388b6ab26dcf --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/checks.json @@ -0,0 +1,219 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~(B | H)", + "B -> ~H", + "~S | ~B", + "~H & B -> S" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "B", + "H" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "H & M", + "B | ~S -> M | H", + "S | H", + "S -> H", + "H <-> B" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "B", + "H", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "M <-> H", + "H <-> ~B | M", + "~M | ~H", + "~S <-> ~H" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "B" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "H", + "M", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET04", + "SET05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0048/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0048/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..16f7e12aefae7daaacfb13611cea9a61c6b20461 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/environment/workdir/sentence_sets.json @@ -0,0 +1,61 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 6", + "sentences": [ + "D | M", + "~H & D", + "(~D -> M) -> M | H", + "H & D" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 3", + "sentences": [ + "~M | D", + "~K | H -> M -> H", + "(D | M) & K", + "~M & ~D" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 4", + "sentences": [ + "~D | ~H", + "D -> ~K <-> ~K -> ~H", + "K <-> D" + ] + }, + { + "id": "SET04", + "source": "Sheet 2, question 15", + "sentences": [ + "H -> ~D <-> M & H", + "~H -> ~M", + "~M", + "H -> D" + ] + }, + { + "id": "SET05", + "source": "Sheet 2, question 1", + "sentences": [ + "~H & K", + "~(M <-> ~H)", + "~M | K" + ] + }, + { + "id": "SET06", + "source": "Sheet 3, question 10", + "sentences": [ + "K | ~M", + "~H <-> K", + "~(M | ~H)", + "K <-> D", + "D <-> ~K" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0057/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4dfa8dbdbe9c419d5dd405cc58992e0e25a5003c --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 57 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4d5bca40ccea6749ca67f6fa432ab20424e82a18 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/checks.json @@ -0,0 +1,217 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~D | ~H", + "D -> ~K <-> ~K -> ~H", + "K <-> D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "D", + "H", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "H -> ~D <-> M & H", + "~H -> ~M", + "~M", + "H -> D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "D", + "H" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "~H & K", + "~(M <-> ~H)", + "~M | K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "H", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0057/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0057/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..f30b2d1672d32f6ae8129848cc1014bc41e1be05 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/environment/workdir/sentence_sets.json @@ -0,0 +1,67 @@ +[ + { + "id": "SET01", + "source": "Sheet 1, question 1", + "sentences": [ + "S -> J -> C", + "J <-> C", + "~(J | ~S)", + "~S <-> J" + ] + }, + { + "id": "SET02", + "source": "Sheet 4, question 2", + "sentences": [ + "C | J", + "~J | S", + "J -> C <-> J & ~E", + "~E | S", + "~J & C" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 2", + "sentences": [ + "C | E", + "S <-> E", + "~E | C", + "C & J", + "C & E" + ] + }, + { + "id": "SET04", + "source": "Sheet 1, question 7", + "sentences": [ + "C | ~E", + "S -> J", + "~S -> E", + "~E -> C", + "(~C -> E) & (E -> S)" + ] + }, + { + "id": "SET05", + "source": "Sheet 3, question 11", + "sentences": [ + "(S | ~E) & (J & E)", + "~J & E", + "J & ~S", + "S | ~C", + "~(E & J)" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 11", + "sentences": [ + "J | S", + "J -> ~C", + "(J -> ~E) & (C <-> J)", + "(~C <-> E) <-> S", + "~(J | ~C)" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0066/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf598eb50ca68ffdea7811b4c89ed2a88743de9c --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 66 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d64c49fb86f2df6db931841ff4b5fb82a0607656 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/checks.json @@ -0,0 +1,221 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "S -> J -> C", + "J <-> C", + "~(J | ~S)", + "~S <-> J" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "C", + "J" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "C | E", + "S <-> E", + "~E | C", + "C & J", + "C & E" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "C", + "E", + "J", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "C | ~E", + "S -> J", + "~S -> E", + "~E -> C", + "(~C -> E) & (E -> S)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "C", + "J", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET05", + "SET06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0066/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0066/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..bdb0ae36c1e294f76a07563054b0f5e7a8235fcc --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/environment/workdir/sentence_sets.json @@ -0,0 +1,64 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 18", + "sentences": [ + "S -> C", + "~P", + "~R & C", + "S | C", + "S <-> ~P" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 10", + "sentences": [ + "~R", + "~S & ~P", + "P | C -> (S <-> R)", + "~C -> P" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 6", + "sentences": [ + "R & P", + "~P | ~C", + "C & P", + "R | ~S" + ] + }, + { + "id": "SET04", + "source": "Sheet 6, question 7", + "sentences": [ + "~R & S", + "(P | R) <-> C", + "R <-> C", + "~S & R" + ] + }, + { + "id": "SET05", + "source": "Sheet 3, question 9", + "sentences": [ + "P | ~R", + "C | P", + "(S -> R) | ~C", + "~C & S", + "P <-> C" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 4", + "sentences": [ + "S & ~C", + "~R | ~C | S", + "R | C", + "P & R" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/instruction.md b/tasks/argument-check/argument-check-consistency-d2-t0075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2740f274cd63c40bd38927dbfd34ee440468c3e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/instruction.md @@ -0,0 +1,15 @@ +# Argument check: consistency + +`sentence_sets.json` holds 6 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d2-t0075/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d2-t0075/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/task.toml b/tasks/argument-check/argument-check-consistency-d2-t0075/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf47628a4c732889009b86fce25bf299e0ab2163 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 75 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/tests/checks.json b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8716961632c36185252a42cb0c77f4702b1cc49f --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/checks.json @@ -0,0 +1,224 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "S -> C", + "~P", + "~R & C", + "S | C", + "S <-> ~P" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "C", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "P", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "~R", + "~S & ~P", + "P | C -> (S <-> R)", + "~C -> P" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "C" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "P", + "R", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "S & ~C", + "~R | ~C | S", + "R | C", + "P & R" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "P", + "R", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "C" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04", + "SET05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/tests/test.sh b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/tests/validators.py b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d2-t0075/tests/verify.py b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d2-t0075/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..fae66ba40e5983e5c999b974b5ee7584846990af --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/environment/workdir/sentence_sets.json @@ -0,0 +1,74 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 19", + "sentences": [ + "~P & D", + "~(E->~D)", + "~(M | ~P)", + "D <-> ~M" + ] + }, + { + "id": "SET02", + "source": "Sheet 1, question 12", + "sentences": [ + "H <-> ~M", + "~H|P<->M", + "~M | ~P", + "~E -> ~M & P" + ] + }, + { + "id": "SET03", + "source": "Sheet 2, question 11", + "sentences": [ + "D -> A", + "A & P", + "P&H", + "P | ~H" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 4", + "sentences": [ + "(A -> H) | (H | ~A)", + "~D", + "(P->D)|(~E->~P)", + "D -> A <-> H & D", + "P | A" + ] + }, + { + "id": "SET05", + "source": "Sheet 2, question 19", + "sentences": [ + "D <-> P", + "(~M -> E) | (D | A)", + "~P & D", + "~D -> E", + "~(P | ~E)" + ] + }, + { + "id": "SET06", + "source": "Sheet 5, question 17", + "sentences": [ + "D <-> ~M", + "~M", + "P & ~H", + "D <-> E", + "~D -> ~A" + ] + }, + { + "id": "SET07", + "source": "Sheet 1, question 13", + "sentences": [ + "~M | ~D", + "(M -> A) & (E | ~M)", + "(D | A) & (M & D)" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/instruction.md b/tasks/argument-check/argument-check-consistency-d3-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-e0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-e0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/task.toml b/tasks/argument-check/argument-check-consistency-d3-e0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e8264aeb4aa2913c5ca6a3f957c4bd06e720f5e --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10006 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..377d94c811a665211004589537192ab7b0590f5d --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/checks.json @@ -0,0 +1,280 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET01.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "H <-> ~M", + "~H|P<->M", + "~M | ~P", + "~E -> ~M & P" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "E" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "D -> A", + "A & P", + "P&H", + "P | ~H" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "A", + "H", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET04.restoring", + "type": "set", + "value": [ + 2, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET05.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "D <-> ~M", + "~M", + "P & ~H", + "D <-> E", + "~D -> ~A" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "D", + "E", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "H", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET04", + "SET05", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-e0006/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..0c50243f10362e8eee19b26914aa537787371358 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/environment/workdir/sentence_sets.json @@ -0,0 +1,75 @@ +[ + { + "id": "SET01", + "source": "Sheet 4, question 5", + "sentences": [ + "~G -> J", + "~M & G", + "~J | ~M", + "(M <-> J) <-> ~D & M" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 7", + "sentences": [ + "B|C", + "D & G", + "C -> ~G", + "~B", + "B <-> ~J" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 16", + "sentences": [ + "~B", + "G | M", + "~G | B", + "~M", + "C & B | (~J -> M)", + "G -> D" + ] + }, + { + "id": "SET04", + "source": "Sheet 2, question 2", + "sentences": [ + "~(~C | B)", + "D & G <-> G -> D", + "~D" + ] + }, + { + "id": "SET05", + "source": "Sheet 6, question 3", + "sentences": [ + "C -> J", + "B <-> ~M", + "G | ~C", + "~J & M & (C <-> G)" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 11", + "sentences": [ + "(B | ~M) & (~J -> ~M)", + "J | D", + "(G -> ~J) & (M | ~J)", + "D -> ~G", + "M & ~C" + ] + }, + { + "id": "SET07", + "source": "Sheet 8, question 11", + "sentences": [ + "G | D | (B | M)", + "M & ~G & (~D | G)", + "~J -> ~M", + "(B -> D) & (M & G)" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/instruction.md b/tasks/argument-check/argument-check-consistency-d3-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-e0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/task.toml b/tasks/argument-check/argument-check-consistency-d3-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1871f04f6533f57efcf06d8c1e78bf6b89ef616 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "eval"] +isced_f = "0223" +family = "consistency" +split = "eval" +seed = 10015 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..84d407e59702a6db4e1bcd819a1664d8995679f5 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/checks.json @@ -0,0 +1,310 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~G -> J", + "~M & G", + "~J | ~M", + "(M <-> J) <-> ~D & M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "G", + "J" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 1, + 2, + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET03.restoring", + "type": "set", + "value": [ + 1, + 2, + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~(~C | B)", + "D & G <-> G -> D", + "~D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "C", + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "B", + "D" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "C -> J", + "B <-> ~M", + "G | ~C", + "~J & M & (C <-> G)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "B", + "C", + "G", + "J" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "(B | ~M) & (~J -> ~M)", + "J | D", + "(G -> ~J) & (M | ~J)", + "D -> ~G", + "M & ~C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "B", + "J", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "C", + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 2, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET03", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-e0015/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-e0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..68bf8145135f5046aeaa0df3b900319a36b3ef12 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/environment/workdir/sentence_sets.json @@ -0,0 +1,73 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 4", + "sentences": [ + "K -> T <-> ~F & K", + "K <-> ~G", + "G<->~D", + "~F | K" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 3", + "sentences": [ + "~C & F & (~C <-> G)", + "F -> C", + "C & D", + "~D" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 16", + "sentences": [ + "(G | K) <-> G <-> D", + "D&~G", + "F | G", + "~G" + ] + }, + { + "id": "SET04", + "source": "Sheet 1, question 13", + "sentences": [ + "T|F", + "K", + "K | F <-> F | ~K", + "T | ~C" + ] + }, + { + "id": "SET05", + "source": "Sheet 9, question 1", + "sentences": [ + "T <-> ~F", + "F&(D&K)", + "~(T <-> K)", + "~T -> C" + ] + }, + { + "id": "SET06", + "source": "Sheet 3, question 5", + "sentences": [ + "D & (~K & ~G)", + "C <-> ~D", + "C&(F&K)", + "~D", + "~T -> ~G" + ] + }, + { + "id": "SET07", + "source": "Sheet 5, question 13", + "sentences": [ + "~K | F", + "G <-> F", + "G | F", + "~F & ~D" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c34751eebeac88bcd1309e4301b8510362232562 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 6 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f5dd7640bcde23740f2218472c0ddda2b04f7484 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/checks.json @@ -0,0 +1,299 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "K -> T <-> ~F & K", + "K <-> ~G", + "G<->~D", + "~F | K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "D", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "(G | K) <-> G <-> D", + "D&~G", + "F | G", + "~G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "D", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "G", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "T|F", + "K", + "K | F <-> F | ~K", + "T | ~C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "F", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "T <-> ~F", + "F&(D&K)", + "~(T <-> K)", + "~T -> C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "C", + "D", + "F", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.restoring", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 2, + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET06", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0006/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..7f9d4dd0b5b08bf2b0b0d17f986a889761e9acf5 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/environment/workdir/sentence_sets.json @@ -0,0 +1,78 @@ +[ + { + "id": "SET01", + "source": "Sheet 3, question 12", + "sentences": [ + "~(~B & E)", + "B & K", + "~K & E | ~E & D" + ] + }, + { + "id": "SET02", + "source": "Sheet 6, question 19", + "sentences": [ + "M & D -> (T <-> E)", + "(B <-> M) | (T -> D)", + "K & T", + "T->M", + "D <-> ~M" + ] + }, + { + "id": "SET03", + "source": "Sheet 6, question 2", + "sentences": [ + "D | B", + "T -> ~K", + "(D<->T)|(~D<->~B)", + "~E&(T->D)", + "~B | T" + ] + }, + { + "id": "SET04", + "source": "Sheet 6, question 19", + "sentences": [ + "~E & M", + "~M | K", + "~E", + "M -> T <-> ~K" + ] + }, + { + "id": "SET05", + "source": "Sheet 7, question 4", + "sentences": [ + "~E | B", + "E | T | K & B", + "E & B", + "B | (K | ~D)", + "~E & ~D", + "M&T" + ] + }, + { + "id": "SET06", + "source": "Sheet 6, question 4", + "sentences": [ + "~D -> T", + "E | T", + "M & ~E", + "K&D", + "(E <-> B) <-> B & E", + "B <-> E" + ] + }, + { + "id": "SET07", + "source": "Sheet 6, question 19", + "sentences": [ + "~K", + "B <-> T", + "T & ~B", + "M & ~K", + "(T & E) | E & B" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1cd4807ea8eb7a7756051e96e7698284f0423327 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 15 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..37832b9b3f29cb6b0171ad5b0ccef756e13c0e31 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/checks.json @@ -0,0 +1,308 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~(~B & E)", + "B & K", + "~K & E | ~E & D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "B", + "D", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "E" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "M & D -> (T <-> E)", + "(B <-> M) | (T -> D)", + "K & T", + "T->M", + "D <-> ~M" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "B", + "K", + "M", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "D" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "D | B", + "T -> ~K", + "(D<->T)|(~D<->~B)", + "~E&(T->D)", + "~B | T" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "D", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "E", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~E & M", + "~M | K", + "~E", + "M -> T <-> ~K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "K", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "E", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET05.restoring", + "type": "set", + "value": [ + 3, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET06.restoring", + "type": "set", + "value": [ + 3, + 5, + 6 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET05", + "SET06", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0015/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..b4d5697a4e72a29c5bfa69066dcb038db2414f8a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/environment/workdir/sentence_sets.json @@ -0,0 +1,80 @@ +[ + { + "id": "SET01", + "source": "Sheet 9, question 10", + "sentences": [ + "C <-> ~L", + "(P -> ~C) & (G & L)", + "(~G | H) & (~L | ~P)", + "P | C", + "C&(~P&H)" + ] + }, + { + "id": "SET02", + "source": "Sheet 9, question 7", + "sentences": [ + "~(~P -> G)", + "H&G", + "G & ~N", + "L & (~C <-> N)", + "C <-> G", + "C" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 14", + "sentences": [ + "C | L", + "L <-> G", + "(P <-> H) & C", + "H -> G", + "~C & L <-> ~N", + "~P -> C <-> ~N | H" + ] + }, + { + "id": "SET04", + "source": "Sheet 4, question 4", + "sentences": [ + "H & P", + "(N -> ~H) & (P & ~C)", + "N | H", + "~(P & N)" + ] + }, + { + "id": "SET05", + "source": "Sheet 9, question 12", + "sentences": [ + "~(~P | ~H)", + "C->L", + "H -> L", + "(~N->L)->(~L|G)", + "N&C", + "L->N" + ] + }, + { + "id": "SET06", + "source": "Sheet 1, question 16", + "sentences": [ + "H<->C->~P", + "H | G <-> ~P", + "N -> P", + "(~H|N)&(N|H)", + "P -> ~N" + ] + }, + { + "id": "SET07", + "source": "Sheet 3, question 7", + "sentences": [ + "~L", + "~G & H", + "H & G", + "P & C" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0024/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c8babae5581e890a55f7cc4c592bcc750f2259a --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 24 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d1d24d6b19ada812a4aabd08726051b70bb57e44 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/checks.json @@ -0,0 +1,288 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET01.restoring", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "C | L", + "L <-> G", + "(P <-> H) & C", + "H -> G", + "~C & L <-> ~N", + "~P -> C <-> ~N | H" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "C", + "G", + "H", + "L", + "N", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "H & P", + "(N -> ~H) & (P & ~C)", + "N | H", + "~(P & N)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "H", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "C", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "~(~P | ~H)", + "C->L", + "H -> L", + "(~N->L)->(~L|G)", + "N&C", + "L->N" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "C", + "G", + "H", + "L", + "N", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.restoring", + "type": "set", + "value": [ + 3, + 4, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02", + "SET06", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0024/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0024/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..68cfc706d337db0a9ebac718e23cf043a1172076 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/environment/workdir/sentence_sets.json @@ -0,0 +1,77 @@ +[ + { + "id": "SET01", + "source": "Sheet 2, question 16", + "sentences": [ + "(Q | ~H) & (~H -> F)", + "D|T<->~K", + "(T -> ~D) & (F | D)", + "~D <-> Q", + "~Q <-> ~K" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 19", + "sentences": [ + "~Q -> D", + "K & ~T", + "D | H", + "F & ~T", + "K <-> T", + "(K&F)<->D" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 11", + "sentences": [ + "D -> H", + "~K -> T", + "(~K&Q)&(D|T)", + "(~D & T) & (Q & K)" + ] + }, + { + "id": "SET04", + "source": "Sheet 1, question 7", + "sentences": [ + "T & ~Q", + "F|D<->(T|D)", + "~Q & T | T & ~F" + ] + }, + { + "id": "SET05", + "source": "Sheet 5, question 17", + "sentences": [ + "~D & (F -> T)", + "H <-> D", + "~Q <-> T", + "~(K&~Q)", + "~T & F", + "F | ~T | ~K" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 6", + "sentences": [ + "~F -> H", + "~H", + "D & T", + "D & (Q -> ~F)" + ] + }, + { + "id": "SET07", + "source": "Sheet 4, question 4", + "sentences": [ + "K|(D|~H)", + "F | ~H", + "~H", + "K<->~D", + "Q & ~K" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0033/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b330961afebe5fd7e8c9a0a300dd4e35d73d120b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 33 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..71feb979c8574ac6c795ec695d9ca584bb1d84ef --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/checks.json @@ -0,0 +1,303 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "(Q | ~H) & (~H -> F)", + "D|T<->~K", + "(T -> ~D) & (F | D)", + "~D <-> Q", + "~Q <-> ~K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 2, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.restoring", + "type": "set", + "value": [ + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "T & ~Q", + "F|D<->(T|D)", + "~Q & T | T & ~F" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET05.restoring", + "type": "set", + "value": [ + 1, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "~F -> H", + "~H", + "D & T", + "D & (Q -> ~F)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "D", + "F", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "H", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET07", + "sentences": [ + "K|(D|~H)", + "F | ~H", + "~H", + "K<->~D", + "Q & ~K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET07.forced_true", + "type": "set", + "value": [ + "D", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.forced_false", + "type": "set", + "value": [ + "H", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET03", + "SET05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0033/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0033/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..1d5c10e9fe9d57cabd80d02b86de8736bcd965ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/environment/workdir/sentence_sets.json @@ -0,0 +1,74 @@ +[ + { + "id": "SET01", + "source": "Sheet 7, question 15", + "sentences": [ + "K -> ~R", + "(K <-> M) -> M -> C", + "K&R" + ] + }, + { + "id": "SET02", + "source": "Sheet 7, question 20", + "sentences": [ + "K | C", + "C | E", + "M <-> L | ~R", + "~(~M -> R)", + "~C|E" + ] + }, + { + "id": "SET03", + "source": "Sheet 8, question 12", + "sentences": [ + "~R & (E -> ~M)", + "E&C", + "~L", + "E <-> K", + "L & K", + "K -> ~L" + ] + }, + { + "id": "SET04", + "source": "Sheet 7, question 19", + "sentences": [ + "C -> E", + "C | ~L", + "~K & ~C" + ] + }, + { + "id": "SET05", + "source": "Sheet 6, question 5", + "sentences": [ + "L & C", + "~R", + "R -> M", + "R | M & K" + ] + }, + { + "id": "SET06", + "source": "Sheet 9, question 7", + "sentences": [ + "R & M", + "~L -> M", + "L -> C", + "~(R -> C)" + ] + }, + { + "id": "SET07", + "source": "Sheet 7, question 9", + "sentences": [ + "M&~E", + "~K", + "(~L <-> ~M) & (C & E)", + "L<->C", + "K | ~E" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0042/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6449f0f9b74366c4bcc817a481b23548a9ceff5c --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 42 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3a86463a335755a87b38d2824e60e93df9c48ff0 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/checks.json @@ -0,0 +1,278 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET03.restoring", + "type": "set", + "value": [ + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "C -> E", + "C | ~L", + "~K & ~C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [ + "C", + "K", + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "L & C", + "~R", + "R -> M", + "R | M & K" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "C", + "K", + "L", + "M" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "R & M", + "~L -> M", + "L -> C", + "~(R -> C)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "M", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "C", + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET01", + "SET02", + "SET03", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0042/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0042/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..3da5ea5c5ef1f9bc45633bb3c05475d7b6cd6d2f --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/environment/workdir/sentence_sets.json @@ -0,0 +1,80 @@ +[ + { + "id": "SET01", + "source": "Sheet 2, question 3", + "sentences": [ + "~G -> ~F", + "G <-> Q", + "(~G -> ~F) -> ~F -> Q", + "P -> C", + "~P <-> F <-> ~C" + ] + }, + { + "id": "SET02", + "source": "Sheet 1, question 3", + "sentences": [ + "G & ~Q", + "R & ~P", + "~R <-> ~Q", + "(P -> F) | (P -> G)", + "~P | G" + ] + }, + { + "id": "SET03", + "source": "Sheet 9, question 1", + "sentences": [ + "P -> G", + "F | Q", + "~Q <-> G", + "(F -> C) -> C | G", + "~G -> ~C <-> ~P" + ] + }, + { + "id": "SET04", + "source": "Sheet 9, question 15", + "sentences": [ + "~P | (R -> G)", + "P & R", + "Q | C", + "(~G -> Q) | C", + "R | Q" + ] + }, + { + "id": "SET05", + "source": "Sheet 9, question 7", + "sentences": [ + "C -> ~P", + "G -> P", + "~F & P", + "P & R", + "G|C", + "~C | G -> C -> Q" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 15", + "sentences": [ + "~R & (Q & ~C)", + "~(R & ~F)", + "~G", + "Q&R->~G", + "F & G & (C | F)" + ] + }, + { + "id": "SET07", + "source": "Sheet 6, question 5", + "sentences": [ + "P <-> G", + "~P | (G & Q)", + "~(~P -> G)", + "F & G", + "R <-> F" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0051/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4aad09ec6e7c5a96475e54df1b4aea966ece5391 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 51 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4d0f21fe9bca3851abd1b143438032b97be657dd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/checks.json @@ -0,0 +1,305 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~G -> ~F", + "G <-> Q", + "(~G -> ~F) -> ~F -> Q", + "P -> C", + "~P <-> F <-> ~C" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "G", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "P -> G", + "F | Q", + "~Q <-> G", + "(F -> C) -> C | G", + "~G -> ~C <-> ~P" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [ + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "~P | (R -> G)", + "P & R", + "Q | C", + "(~G -> Q) | C", + "R | Q" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "G", + "P", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "C -> ~P", + "G -> P", + "~F & P", + "P & R", + "G|C", + "~C | G -> C -> Q" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "G", + "P", + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "C", + "F" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET06.restoring", + "type": "set", + "value": [ + 3, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET06", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0051/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0051/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..b68e7b2e28d30a0cc38330c92b9ee1843637bb99 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/environment/workdir/sentence_sets.json @@ -0,0 +1,69 @@ +[ + { + "id": "SET01", + "source": "Sheet 1, question 12", + "sentences": [ + "~S <-> ~L", + "~P -> ~L", + "K | F", + "L & F" + ] + }, + { + "id": "SET02", + "source": "Sheet 9, question 16", + "sentences": [ + "~D -> ~K", + "L & (~F & K)", + "~K&~D" + ] + }, + { + "id": "SET03", + "source": "Sheet 7, question 19", + "sentences": [ + "~F -> L", + "F & S", + "~(F->~D)" + ] + }, + { + "id": "SET04", + "source": "Sheet 7, question 7", + "sentences": [ + "L <-> F", + "~L", + "(P -> ~L) & ~F", + "L & ~S", + "(K -> ~P) -> ~D" + ] + }, + { + "id": "SET05", + "source": "Sheet 7, question 9", + "sentences": [ + "~L", + "~D & ~K | (K -> D)", + "~L | K -> (K & P)" + ] + }, + { + "id": "SET06", + "source": "Sheet 4, question 17", + "sentences": [ + "~K", + "P <-> ~D | F", + "(D -> P) & (~P | F)", + "~K & ~F -> D" + ] + }, + { + "id": "SET07", + "source": "Sheet 7, question 18", + "sentences": [ + "~P & D & K", + "~L", + "~P & L" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0060/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..27a1e0d3efa58fe201afb8892c43df394d9fb9e0 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 60 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d45569425f49764874db012f5813dac1cd927b5b --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/checks.json @@ -0,0 +1,298 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~S <-> ~L", + "~P -> ~L", + "K | F", + "L & F" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "F", + "L", + "P", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET03", + "sentences": [ + "~F -> L", + "F & S", + "~(F->~D)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_true", + "type": "set", + "value": [ + "D", + "F", + "S" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET04.restoring", + "type": "set", + "value": [ + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "~L", + "~D & ~K | (K -> D)", + "~L | K -> (K & P)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "D", + "K", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "~K", + "P <-> ~D | F", + "(D -> P) & (~P | F)", + "~K & ~F -> D" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "F", + "P" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET04", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0060/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0060/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..37b8bcd040d91ece83461f2e6034b7996a520e57 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/environment/workdir/sentence_sets.json @@ -0,0 +1,77 @@ +[ + { + "id": "SET01", + "source": "Sheet 7, question 4", + "sentences": [ + "~G | A", + "(~L->G)&(N->A)", + "~G & (~A <-> ~D)", + "A | ~D & L", + "~G" + ] + }, + { + "id": "SET02", + "source": "Sheet 3, question 7", + "sentences": [ + "A & ~L -> (L <-> G)", + "A->G", + "~D & ~A -> G -> ~N", + "A & ~G", + "N & L" + ] + }, + { + "id": "SET03", + "source": "Sheet 4, question 2", + "sentences": [ + "~N", + "~D->(L&N)", + "~L&N&(N|A)" + ] + }, + { + "id": "SET04", + "source": "Sheet 4, question 12", + "sentences": [ + "K & D", + "K->G", + "L | ~D", + "K & G" + ] + }, + { + "id": "SET05", + "source": "Sheet 5, question 3", + "sentences": [ + "~G&L", + "G|(D|K)", + "~K <-> ~D", + "~(N&G)", + "N -> G", + "(A & ~L) <-> (L | G)" + ] + }, + { + "id": "SET06", + "source": "Sheet 8, question 18", + "sentences": [ + "G <-> K", + "A <-> N", + "~D & L", + "(~D -> ~K) & (G <-> ~L)", + "L|N", + "L & (~N -> K)" + ] + }, + { + "id": "SET07", + "source": "Sheet 9, question 7", + "sentences": [ + "L->G<->~A", + "~K|G->(A<->K)", + "~A & L", + "L & K" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0069/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b25385a0e0c59356ab45ce46e9e16b3e80874d59 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 69 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4d7d72224791fadb8cc3129b7642335a25312fa8 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/checks.json @@ -0,0 +1,286 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "~G | A", + "(~L->G)&(N->A)", + "~G & (~A <-> ~D)", + "A | ~D & L", + "~G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "G" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET02.restoring", + "type": "set", + "value": [ + 2, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET03.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET04", + "sentences": [ + "K & D", + "K->G", + "L | ~D", + "K & G" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_true", + "type": "set", + "value": [ + "D", + "G", + "K", + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET04.forced_false", + "type": "set", + "value": [], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "sets.SET05.restoring", + "type": "set", + "value": [ + 1, + 6 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "G <-> K", + "A <-> N", + "~D & L", + "(~D -> ~K) & (G <-> ~L)", + "L|N", + "L & (~N -> K)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "A", + "L", + "N" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "D", + "G", + "K" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 1, + 2, + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET02", + "SET03", + "SET05", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0069/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0069/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/environment/Dockerfile b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/sentence_sets.json b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/sentence_sets.json new file mode 100644 index 0000000000000000000000000000000000000000..6ce4397ee11e53a953baa2d08e54e5a5022dc1cb --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/environment/workdir/sentence_sets.json @@ -0,0 +1,72 @@ +[ + { + "id": "SET01", + "source": "Sheet 5, question 3", + "sentences": [ + "L -> ~H <-> H <-> ~R", + "~H", + "Q <-> H" + ] + }, + { + "id": "SET02", + "source": "Sheet 8, question 6", + "sentences": [ + "H & ~T", + "R -> T", + "L" + ] + }, + { + "id": "SET03", + "source": "Sheet 1, question 9", + "sentences": [ + "T & Q & (D -> ~L)", + "L&~H", + "~(D | T)", + "~D | ~H", + "~(~D|~Q)" + ] + }, + { + "id": "SET04", + "source": "Sheet 7, question 10", + "sentences": [ + "~Q", + "H -> D -> ~R", + "Q & R", + "T <-> ~R" + ] + }, + { + "id": "SET05", + "source": "Sheet 1, question 17", + "sentences": [ + "(Q -> D) & (T | D)", + "D | ~R | (T | Q)", + "~L <-> D", + "D -> T <-> R", + "~(~Q -> R)" + ] + }, + { + "id": "SET06", + "source": "Sheet 6, question 3", + "sentences": [ + "~(~D | R)", + "R | H", + "D&L" + ] + }, + { + "id": "SET07", + "source": "Sheet 8, question 9", + "sentences": [ + "~D|~H", + "~R | H", + "D & T", + "(T <-> ~H) -> R -> Q", + "(D <-> Q) & ~T" + ] + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/instruction.md b/tasks/argument-check/argument-check-consistency-d3-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..484acca98d671e0d3e6e44e00cec1732dd816684 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/instruction.md @@ -0,0 +1,16 @@ +# Argument check: consistency + +`sentence_sets.json` holds 7 sets of sentences in propositional logic. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every set with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `sets`: an object keyed by set id. For each set give + - `satisfiable`: `true` or `false`. + - `models`: the number of rows in which every sentence of the set is true, as an integer (0 if unsatisfiable). + - `most_true_together`: the largest number of sentences of the set that are true in one and the same row, as an integer (for a satisfiable set this is the number of sentences). + - `valuation`: for a satisfiable set, one model written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the set). Any model is accepted. For an unsatisfiable set give `null`. + - `forced_true` and `forced_false`: for a satisfiable set only, the lists of atoms that are true in every model of the set and false in every model of the set (any order; empty lists if none). + - `restoring`: for an unsatisfiable set only, the list of sentence numbers (1 for the first sentence in the file, 2 for the second, and so on) such that deleting that one sentence and keeping the others leaves a satisfiable set. Any order; an empty list if none. +- `unsatisfiable_ids`: list of the ids of the unsatisfiable sets (any order). diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/solution/oracle.py b/tasks/argument-check/argument-check-consistency-d3-t0078/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/solution/solve.sh b/tasks/argument-check/argument-check-consistency-d3-t0078/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/task.toml b/tasks/argument-check/argument-check-consistency-d3-t0078/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bcaa37b1e22f215a3b44f27d001283eef15cb8e2 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "consistency", "isced-0223", "train"] +isced_f = "0223" +family = "consistency" +split = "train" +seed = 78 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/tests/checks.json b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d65c8623402f003745af8d5e5562ec06b201d7bf --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/checks.json @@ -0,0 +1,300 @@ +[ + { + "path": "sets.SET01.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET01.models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "sets.SET01.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET01", + "sentences": [ + "L -> ~H <-> H <-> ~R", + "~H", + "Q <-> H" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_true", + "type": "set", + "value": [ + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET01.forced_false", + "type": "set", + "value": [ + "H", + "Q" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET02.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET02.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET02", + "sentences": [ + "H & ~T", + "R -> T", + "L" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_true", + "type": "set", + "value": [ + "H", + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET02.forced_false", + "type": "set", + "value": [ + "R", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET03.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET03.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET03.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET03.restoring", + "type": "set", + "value": [], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET04.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET04.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET04.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "sets.SET04.restoring", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "sets.SET05.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET05.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET05.most_true_together", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET05", + "sentences": [ + "(Q -> D) & (T | D)", + "D | ~R | (T | Q)", + "~L <-> D", + "D -> T <-> R", + "~(~Q -> R)" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_true", + "type": "set", + "value": [ + "D" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET05.forced_false", + "type": "set", + "value": [ + "L", + "Q", + "R", + "T" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.satisfiable", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "sets.SET06.models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "sets.SET06.most_true_together", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "satisfying_valuation", + "args": { + "id": "SET06", + "sentences": [ + "~(~D | R)", + "R | H", + "D&L" + ] + }, + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_true", + "type": "set", + "value": [ + "D", + "H", + "L" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET06.forced_false", + "type": "set", + "value": [ + "R" + ], + "item": "str", + "weight": 1.0 + }, + { + "path": "sets.SET07.satisfiable", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "sets.SET07.models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "sets.SET07.most_true_together", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "sets.SET07.restoring", + "type": "set", + "value": [ + 3, + 5 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "unsatisfiable_ids", + "type": "set", + "value": [ + "SET03", + "SET04", + "SET07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/tests/test.sh b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/tests/validators.py b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-consistency-d3-t0078/tests/verify.py b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-consistency-d3-t0078/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..c3adcdf60b40e201761353c0f573de1c81d7273b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(J -> F) & (J | F)", + "right": "~(~(J -> F) | (J | F))" + }, + { + "id": "PAIR02", + "left": "F & (~J -> Q)", + "right": "F & ~(~J & ~Q)" + }, + { + "id": "PAIR03", + "left": "Q <-> (~F | J)", + "right": "(Q & (~F | J)) | (~Q & ~(~F | J))" + }, + { + "id": "PAIR04", + "left": "~(~(~J <-> Q) | (J | ~Q))", + "right": "(~J <-> Q) & (J | ~Q)" + }, + { + "id": "PAIR05", + "left": "~(~Q & F) -> (~J | Q)", + "right": "(Q | ~F) -> (~J | Q)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/task.toml b/tasks/argument-check/argument-check-equivalence-d1-e0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..069735d174209732aa476dc6c8a6c3ed93df6b29 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10001 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..82559b0aa822218378aa1d78fb9085622e5c2d65 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(J -> F) & (J | F)", + "right": "~(~(J -> F) | (J | F))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~(~(~J <-> Q) | (J | ~Q))", + "right": "(~J <-> Q) & (J | ~Q)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..f2631a6542c55d01f7d58f3d5eaa9b9280e85e9e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "~((R | P) -> ~M)", + "right": "(R | P) & M" + }, + { + "id": "PAIR02", + "left": "(R & M) & (R <-> M)", + "right": "(R & M) & (~R <-> M)" + }, + { + "id": "PAIR03", + "left": "~(R -> M)", + "right": "~(R | M)" + }, + { + "id": "PAIR04", + "left": "(~M | R) & (M -> ~R)", + "right": "(~M | R) & (R -> ~M)" + }, + { + "id": "PAIR05", + "left": "((~R -> P) & (P -> ~R)) & (~P & R)", + "right": "(~R <-> P) & (~P & R)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/task.toml b/tasks/argument-check/argument-check-equivalence-d1-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..021458844884a97e590b547791248fb9e927e32a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10010 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c8989dfb03610e845b2126d38aed48fbb77027d4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(R & M) & (R <-> M)", + "right": "(R & M) & (~R <-> M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(R -> M)", + "right": "~(R | M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR04", + "PAIR05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..8751180c2d619c0e83c89fe4ba7c5c3e404c56ee --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "~(F & ~L)", + "right": "~F | ~L" + }, + { + "id": "PAIR02", + "left": "~(~(~B -> L) | ~(F & L))", + "right": "(~B -> L) & (F & L)" + }, + { + "id": "PAIR03", + "left": "~L -> (B | F)", + "right": "~(~L & ~(B | F))" + }, + { + "id": "PAIR04", + "left": "((~L & F) & F) | ((~L & F) & ~L)", + "right": "(~L & F) & (F | ~L)" + }, + { + "id": "PAIR05", + "left": "((L & ~B) & (L | F)) | (~(L & ~B) & (L | F))", + "right": "(L & ~B) <-> (L | F)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/task.toml b/tasks/argument-check/argument-check-equivalence-d1-e0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..efb7dbe15dfadbb33f1a3307302847aa8c31958b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10019 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e5613895895265a93f7931bdacda71248a555b08 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "~(F & ~L)", + "right": "~F | ~L" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "((L & ~B) & (L | F)) | (~(L & ~B) & (L | F))", + "right": "(L & ~B) <-> (L | F)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-e0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..92bbc9db22d3e479a20e8eec3306c23683cb0f69 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(A | K) | (K & A)", + "right": "(A | K) -> (K & A)" + }, + { + "id": "PAIR02", + "left": "K | (H | A)", + "right": "~K -> (H | A)" + }, + { + "id": "PAIR03", + "left": "(H & ~K) | (~H & K)", + "right": "~(~H | K) | (~H & K)" + }, + { + "id": "PAIR04", + "left": "(K & H) | (H & ~A)", + "right": "~(~K | H) | (H & ~A)" + }, + { + "id": "PAIR05", + "left": "(A | K) | (A & K)", + "right": "(A | K) | ~(A -> ~K)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..576ac9126fb536739eccaaac383fdffc53c2bb0c --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 1 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..408d07273cfdfd6e0ef14d31ea52b87d57c4a7bf --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(A | K) | (K & A)", + "right": "(A | K) -> (K & A)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(K & H) | (H & ~A)", + "right": "~(~K | H) | (H & ~A)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..6caa4cfdcc36173bc5a8c1b7287edd3e33c860a3 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(~F | ~E) -> ((E & F) | (~E & ~F))", + "right": "(~F | ~E) -> (E <-> F)" + }, + { + "id": "PAIR02", + "left": "(S -> ~F) | (E & S)", + "right": "(~S -> F) | (E & S)" + }, + { + "id": "PAIR03", + "left": "~(S -> E)", + "right": "~~(~S & E)" + }, + { + "id": "PAIR04", + "left": "(E <-> S) | (~S & F)", + "right": "((E <-> S) | ~S) & ((E <-> S) | F)" + }, + { + "id": "PAIR05", + "left": "(F -> (F -> E)) & (E -> (F -> E))", + "right": "(F | E) -> (F -> E)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..148a7480df1f54543b250f39f7b3eaebfb0b5694 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 10 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f5ac1d0ca5a7cfa1854b4f0834538a286a30553f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(S -> ~F) | (E & S)", + "right": "(~S -> F) | (E & S)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(S -> E)", + "right": "~~(~S & E)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR04", + "PAIR05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..26bd3bf06392b16d40d48b2643184edfa4298a4f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "~Q | M", + "right": "~Q -> ~M" + }, + { + "id": "PAIR02", + "left": "(~N | M) -> ~(~N & ~Q)", + "right": "(~N | M) -> (N | Q)" + }, + { + "id": "PAIR03", + "left": "(~M -> Q) | (~N & ~M)", + "right": "~(~M -> Q) -> (~N & ~M)" + }, + { + "id": "PAIR04", + "left": "(~Q -> M) -> (M & ~N)", + "right": "(~Q -> M) -> ~(M -> N)" + }, + { + "id": "PAIR05", + "left": "((M -> N) & (~N -> M)) -> (M | N)", + "right": "(M <-> N) -> (M | N)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae25f4d48b6df2b9fb99c4150c26759b56befcaf --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 19 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bc68166a4ae6090d08551a2cd14b4c211bff073d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "~Q | M", + "right": "~Q -> ~M" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "((M -> N) & (~N -> M)) -> (M | N)", + "right": "(M <-> N) -> (M | N)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..f18c77d57e3374894f8cd7926fc8d4369287fb12 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "~((M -> S) -> ~J)", + "right": "(M -> S) & J" + }, + { + "id": "PAIR02", + "left": "(J & S) & (~S -> ~M)", + "right": "(J & S) & (S -> M)" + }, + { + "id": "PAIR03", + "left": "~(J -> ~M)", + "right": "~(~J | ~M)" + }, + { + "id": "PAIR04", + "left": "(~S -> ~M) -> (M | S)", + "right": "(~S -> ~M) -> (~M -> S)" + }, + { + "id": "PAIR05", + "left": "~M | ~S", + "right": "~(M | S)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..737f1a455b1e0ec5a90d9fb8bf1af396aa2cb577 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 28 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d100bc688c64bcaccc95031e99b63033ef6530c9 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(J & S) & (~S -> ~M)", + "right": "(J & S) & (S -> M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~M | ~S", + "right": "~(M | S)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0028/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..ca2353d5ae552a34cb2b38ba3d573cb9d9f95aa8 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(J -> ~M) & (J <-> M)", + "right": "~(~(J -> ~M) | (J <-> M))" + }, + { + "id": "PAIR02", + "left": "(~B <-> J) | (~J & B)", + "right": "~(~B <-> J) -> (~J & B)" + }, + { + "id": "PAIR03", + "left": "(M | B) & (~B | ~M)", + "right": "(M -> B) & (~B | ~M)" + }, + { + "id": "PAIR04", + "left": "(M -> ~B) -> (M | J)", + "right": "~((M -> ~B) & ~(M | J))" + }, + { + "id": "PAIR05", + "left": "((M -> J) & (~J -> M)) | (B | ~J)", + "right": "(M <-> J) | (B | ~J)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b3fa0175568307f374f2373fc6f182f75fcc8c5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 37 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..09cb67f74ee15c34b6bb58a7461f9db494c0196b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(J -> ~M) & (J <-> M)", + "right": "~(~(J -> ~M) | (J <-> M))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(M | B) & (~B | ~M)", + "right": "(M -> B) & (~B | ~M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "((M -> J) & (~J -> M)) | (B | ~J)", + "right": "(M <-> J) | (B | ~J)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0037/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..0729a020cdabd44f02fc5650ddc061aca40b395e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(E & D) -> (~E & D)", + "right": "E -> (D -> (~E & D))" + }, + { + "id": "PAIR02", + "left": "(E | G) | ~(~E -> D)", + "right": "(E | G) -> (~E -> D)" + }, + { + "id": "PAIR03", + "left": "(~E & G) & (~E <-> ~D)", + "right": "~(~(~E & G) | ~(~E <-> ~D))" + }, + { + "id": "PAIR04", + "left": "~(~E | (G -> D))", + "right": "E & (G -> D)" + }, + { + "id": "PAIR05", + "left": "(E | ~D) & (~D | G)", + "right": "(E -> D) & (~D | G)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..966f064ef84c32e433898f569400d8a864b40ca8 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 46 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..997985f9fc496aa033a11188c35e75fc4586a969 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(E | G) | ~(~E -> D)", + "right": "(E | G) -> (~E -> D)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~(~E | (G -> D))", + "right": "E & (G -> D)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(E | ~D) & (~D | G)", + "right": "(E -> D) & (~D | G)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0046/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..31ee241aac7372784fcec54050b8e4102d08e3d4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "J <-> (D & R)", + "right": "J <-> ~(~D | ~R)" + }, + { + "id": "PAIR02", + "left": "(R -> J) & ~(~D | ~J)", + "right": "(R -> J) & (D & J)" + }, + { + "id": "PAIR03", + "left": "(R -> ~D) & ~(~D & ~J)", + "right": "(R -> ~D) & (D -> ~J)" + }, + { + "id": "PAIR04", + "left": "((D -> R) & (R -> D)) & ~J", + "right": "(D <-> R) & ~J" + }, + { + "id": "PAIR05", + "left": "(J -> D) & (J -> D)", + "right": "(J -> D) & (D -> J)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0957ddfc102b447555bd74304758db4ea10bb6b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 55 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1be081680a13e964781c5f2055f6a5981c0592e1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(R -> ~D) & ~(~D & ~J)", + "right": "(R -> ~D) & (D -> ~J)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(J -> D) & (J -> D)", + "right": "(J -> D) & (D -> J)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02", + "PAIR04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0055/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..984e9c51dd21f0e0f07f041f5774867584c4c085 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(G & K) | P", + "right": "~(G & K) -> P" + }, + { + "id": "PAIR02", + "left": "(P -> G) | (~P & G)", + "right": "((P -> G) | ~P) & ((P -> G) | G)" + }, + { + "id": "PAIR03", + "left": "(P -> ~K) & G", + "right": "(P | ~K) & G" + }, + { + "id": "PAIR04", + "left": "~(G | P)", + "right": "~G | ~P" + }, + { + "id": "PAIR05", + "left": "(~G -> K) <-> (~P & G)", + "right": "(G -> ~K) <-> (~P & G)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97f9f9a52c6313f24d1f742417c6c72019c76e14 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 64 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..54113f0722c00dcf3ec05bc730324139dca923ee --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(P -> ~K) & G", + "right": "(P | ~K) & G" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~(G | P)", + "right": "~G | ~P" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(~G -> K) <-> (~P & G)", + "right": "(G -> ~K) <-> (~P & G)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0064/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..d96a1ecc39071de413140a30f4cfafabb8833784 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "(F & T) -> (H <-> ~F)", + "right": "(F & T) -> ((H -> ~F) & (~F -> H))" + }, + { + "id": "PAIR02", + "left": "~(~F -> T)", + "right": "~F & ~T" + }, + { + "id": "PAIR03", + "left": "(T & H) | ((~H & ~T) | (H & ~T))", + "right": "(T & H) | (~H <-> ~T)" + }, + { + "id": "PAIR04", + "left": "((T | ~F) -> (F | T)) & (~(F | T) -> (T | ~F))", + "right": "(T | ~F) <-> (F | T)" + }, + { + "id": "PAIR05", + "left": "(H | T) -> (H <-> T)", + "right": "(H | T) -> ((H -> T) & (~T -> H))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0073/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8e6293982927dc0e33849c721f840dfe6e9f9cf8 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 73 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e8217c5414ac5876fd6dd0c5035d4d0f38f27ee8 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(T & H) | ((~H & ~T) | (H & ~T))", + "right": "(T & H) | (~H <-> ~T)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "((T | ~F) -> (F | T)) & (~(F | T) -> (T | ~F))", + "right": "(T | ~F) <-> (F | T)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(H | T) -> (H <-> T)", + "right": "(H | T) -> ((H -> T) & (~T -> H))" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0073/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..b37678c44a1b726963edc6cff006fd97245eed74 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/environment/workdir/pairs.json @@ -0,0 +1,27 @@ +[ + { + "id": "PAIR01", + "left": "~(F & ~B) <-> ~(B | F)", + "right": "(F & ~B) <-> (B | F)" + }, + { + "id": "PAIR02", + "left": "F & B", + "right": "~(~F -> B)" + }, + { + "id": "PAIR03", + "left": "(L -> F) | (B <-> L)", + "right": "~(L & ~F) | (B <-> L)" + }, + { + "id": "PAIR04", + "left": "B <-> ~(~F | L)", + "right": "B <-> (F & L)" + }, + { + "id": "PAIR05", + "left": "~F & (~L & ~B)", + "right": "~(F | (~L & ~B))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/instruction.md b/tasks/argument-check/argument-check-equivalence-d1-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1531bd821e240c6f2848cbebb1ea6d6af9e13f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/instruction.md @@ -0,0 +1,14 @@ +# Argument check: equivalence + +`pairs.json` holds 5 pairs of formulas in propositional logic, `left` and `right`. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/task.toml b/tasks/argument-check/argument-check-equivalence-d1-t0082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c65b2a8ef415e13d6e6bbaebb45cc788c77c5644 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 82 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..45c498d6f3b095ae107715e730f06d03d0572cdd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "F & B", + "right": "~(~F -> B)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "B <-> ~(~F | L)", + "right": "B <-> (F & L)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~F & (~L & ~B)", + "right": "~(F | (~L & ~B))" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d1-t0082/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..209ba9e096627c7ea3701ab216afd03390e4da0f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~Q & ~(F <-> ~G)" + }, + { + "id": "F02", + "formula": "(Q & E) | (F & Q <-> (Q -> ~F))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..0d55e22a353702d79b65d3e07a73a93abb7d6b1a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "Q | E -> ~E -> G", + "right": "(Q -> E) -> (~E -> G)" + }, + { + "id": "PAIR02", + "left": "~E & F & G", + "right": "~(~(~E & F) | ~G)" + }, + { + "id": "PAIR03", + "left": "~E | Q | ~(G -> ~E)", + "right": "~((E & ~Q) & (G -> ~E))" + }, + { + "id": "PAIR04", + "left": "(~F & ~Q | ~G) <-> ((G | Q -> ~G | ~E) & (~G | ~E -> (~G -> Q)))", + "right": "~F & ~Q | ~G <-> G | Q <-> ~G | ~E" + }, + { + "id": "PAIR05", + "left": "~(~Q -> ~F) -> G & ~Q", + "right": "~Q & F | G & ~Q" + }, + { + "id": "PAIR06", + "left": "F & G | (Q -> ~E)", + "right": "F & G -> Q -> ~E" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-e0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/task.toml b/tasks/argument-check/argument-check-equivalence-d2-e0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2cb3838073774e222e10bb6370897142c154bdb1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10004 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..19aec2a92de98f7c88ca07ea96be441d879af583 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "Q | E -> ~E -> G", + "right": "(Q -> E) -> (~E -> G)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~(~Q -> ~F) -> G & ~Q", + "right": "~Q & F | G & ~Q" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "F & G | (Q -> ~E)", + "right": "F & G -> Q -> ~E" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR04" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~Q & ~(F <-> ~G)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(Q & E) | (F & Q <-> (Q -> ~F))", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..31e845b4dc5390c94ef969db0b4150ec217a50e3 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~S & (~J & L) | ((L & J) <-> L -> S)" + }, + { + "id": "F02", + "formula": "(K <-> J) & ~S | (J -> ~K <-> S & J)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..7cf65b41c140f86085a272d40642fb3b9ee58d9b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~J | K | ~(K | ~J) -> (~K -> ~J) | (L -> ~J)", + "right": "(~J | K) | ~K & J -> ((J -> K) | (L -> ~J))" + }, + { + "id": "PAIR02", + "left": "(L & S -> ~S & L) -> ((J -> S) | K & S)", + "right": "(L & S -> ~S & L) -> J | ~S | ~(K -> ~S)" + }, + { + "id": "PAIR03", + "left": "~((S -> ~J) & (S | ~J) & L)", + "right": "(S -> ~J) & (S | ~J) -> ~L" + }, + { + "id": "PAIR04", + "left": "~(L & K | J & L) -> ~((K -> L) -> K | J)", + "right": "(K -> L) | (K | J) -> (L & K | J & L)" + }, + { + "id": "PAIR05", + "left": "~(~(S -> ~J) | ~(~K & S))", + "right": "~((S -> ~J) -> (K | ~S))" + }, + { + "id": "PAIR06", + "left": "(~L & S) -> (J -> L)", + "right": "~L & S -> J | L" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/task.toml b/tasks/argument-check/argument-check-equivalence-d2-e0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b114a4c34445ab88bcb755fe9e2877181c1586ff --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10013 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1f0d2e8847d08a5e7b06b70f2c1e63aa084b8017 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(L & S -> ~S & L) -> ((J -> S) | K & S)", + "right": "(L & S -> ~S & L) -> J | ~S | ~(K -> ~S)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~(L & K | J & L) -> ~((K -> L) -> K | J)", + "right": "(K -> L) | (K | J) -> (L & K | J & L)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "(~L & S) -> (J -> L)", + "right": "~L & S -> J | L" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~S & (~J & L) | ((L & J) <-> L -> S)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(K <-> J) & ~S | (J -> ~K <-> S & J)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..4e514640c1c282a5b3d548e7ad789d3a271aebed --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "((N -> M) -> (N -> ~M)) & ((M -> A) -> ~A -> ~N)" + }, + { + "id": "F02", + "formula": "(~A -> ~M) & ((~A | Q) | M)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..e6c27746cbabea570b242161bcb1c92cee7e218e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "A & (~N -> ~Q)", + "right": "A & (N | ~Q)" + }, + { + "id": "PAIR02", + "left": "(N | M -> M -> A) | (M -> ~A) & N", + "right": "(N -> M -> A) | (M -> M -> A) | ((~M | ~A) & N)" + }, + { + "id": "PAIR03", + "left": "~((A | Q) & (A -> N)) -> ~(Q | M) & ~(~N | A)", + "right": "(Q | M | (~N | A)) -> (A | Q) & (A -> N)" + }, + { + "id": "PAIR04", + "left": "N & M -> (~Q <-> ~N) <-> ~A -> ~M", + "right": "N & M -> ~Q & ~N | (Q & ~N) <-> (~A -> ~M)" + }, + { + "id": "PAIR05", + "left": "(Q <-> M) -> (Q <-> ~N) | ~N & Q", + "right": "~(Q <-> M) | (Q & ~N | ~Q & N | ~N & Q)" + }, + { + "id": "PAIR06", + "left": "(~M | ~Q) & (Q | (~M -> ~N))", + "right": "(~M -> Q) & (Q | (N -> M))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/task.toml b/tasks/argument-check/argument-check-equivalence-d2-e0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..95b3590bbb73f7caddd0c01ffae28afb6f0b2f90 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10022 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f9736cece03580d97d3a2277d28a85daf2ae0498 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(N | M -> M -> A) | (M -> ~A) & N", + "right": "(N -> M -> A) | (M -> M -> A) | ((~M | ~A) & N)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "N & M -> (~Q <-> ~N) <-> ~A -> ~M", + "right": "N & M -> ~Q & ~N | (Q & ~N) <-> (~A -> ~M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "(~M | ~Q) & (Q | (~M -> ~N))", + "right": "(~M -> Q) & (Q | (N -> M))" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "((N -> M) -> (N -> ~M)) & ((M -> A) -> ~A -> ~N)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(~A -> ~M) & ((~A | Q) | M)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-e0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..876d70340c4ead521d76cc6eec9e8700530c0832 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(A <-> T | S) & ((~T | A) <-> T | A)" + }, + { + "id": "F02", + "formula": "(~M <-> S) <-> ~(M & ~A)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..c4be13d967fac29d808a8eabda40353bc29c4d33 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "S | ~A | (~T | S)", + "right": "~(~S & A) | ~(T & S)" + }, + { + "id": "PAIR02", + "left": "~(T | ~M) | (~A | S)", + "right": "~T & M | (A -> S)" + }, + { + "id": "PAIR03", + "left": "(T <-> A) & (~A & M)", + "right": "~((T <-> A) -> ~(~A & M))" + }, + { + "id": "PAIR04", + "left": "((S -> M) & (M | ~S) -> A) & (M | (T | S))", + "right": "((S <-> M) -> A) & (M | (T | S))" + }, + { + "id": "PAIR05", + "left": "(~M | ~T) | S", + "right": "M | ~T | S" + }, + { + "id": "PAIR06", + "left": "~(~M & ~(~T & S))", + "right": "M | (~T & S)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7823ea4a63deb05ed923532dd2f15c9a7db84c73 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 4 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2419c5cea8d38d5c89ade9bf57316e3b35e116d6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "S | ~A | (~T | S)", + "right": "~(~S & A) | ~(T & S)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "((S -> M) & (M | ~S) -> A) & (M | (T | S))", + "right": "((S <-> M) -> A) & (M | (T | S))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(~M | ~T) | S", + "right": "M | ~T | S" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR03", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(A <-> T | S) & ((~T | A) <-> T | A)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(~M <-> S) <-> ~(M & ~A)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..bf4eb528394d26a16b713faaaa4c0e43ff344db7 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(~K -> C) & (C | ~B)" + }, + { + "id": "F02", + "formula": "(M -> B) & K" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..f89f59f195d5542d8d82c4dd7b8d323ebf3b725a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "C | K -> C -> ~(~B <-> M)", + "right": "C | K -> (B <-> M) -> ~C" + }, + { + "id": "PAIR02", + "left": "~(B | M) | (M & ~B <-> ~M | ~C)", + "right": "~(~B -> M) | (~(M & ~B) <-> ~(~M | ~C))" + }, + { + "id": "PAIR03", + "left": "~(~M & (B <-> C))", + "right": "M | (B <-> C)" + }, + { + "id": "PAIR04", + "left": "C & B <-> ~M", + "right": "~(~C | B) <-> ~M" + }, + { + "id": "PAIR05", + "left": "C -> ~(B -> ~K) -> ~K", + "right": "C & K -> (B -> ~K)" + }, + { + "id": "PAIR06", + "left": "(C <-> ~M) | (~K -> M -> ~C)", + "right": "(C <-> ~M) | (K | (C -> ~M))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb4dbf6b172d4a78dac14a478f8299812cd0bc91 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 13 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cbc1839c4307fc804b7d5d000f8826f8275f64c8 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "C | K -> C -> ~(~B <-> M)", + "right": "C | K -> (B <-> M) -> ~C" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(~M & (B <-> C))", + "right": "M | (B <-> C)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "C & B <-> ~M", + "right": "~(~C | B) <-> ~M" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR05", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(~K -> C) & (C | ~B)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(M -> B) & K", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..4fb80f87610a783957f43d0a40b274c2089dc751 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(T <-> S <-> M) | T & ~M & S" + }, + { + "id": "F02", + "formula": "(M -> ~T) & (T & S) | ((M -> S) -> ~T & S)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..23438f5c9addbf48eb624af387f7ddf64d98fa0b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~T -> ~(K & S)", + "right": "T -> (K & S)" + }, + { + "id": "PAIR02", + "left": "(T | S) <-> ~K", + "right": "((T | S) & ~K) | ~(T | S) & K" + }, + { + "id": "PAIR03", + "left": "(S -> K) -> M", + "right": "(~S -> ~K) -> M" + }, + { + "id": "PAIR04", + "left": "(S -> ~M) & T", + "right": "(S | ~M) & T" + }, + { + "id": "PAIR05", + "left": "M & ~T | (~M -> T) | (~M -> S) & T", + "right": "M & ~T | (M | T) | (~M -> S) & T" + }, + { + "id": "PAIR06", + "left": "(M | T) & ~S | ~~(M -> ~T)", + "right": "(M | T) & ~S | (~M | ~T)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d6967088c68af4cc37e77428a92055123d5a3a40 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 22 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..40d8bc93df78c489f9d594a30467850ce620b080 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "~T -> ~(K & S)", + "right": "T -> (K & S)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(S -> K) -> M", + "right": "(~S -> ~K) -> M" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(S -> ~M) & T", + "right": "(S | ~M) & T" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR05", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(T <-> S <-> M) | T & ~M & S", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(M -> ~T) & (T & S) | ((M -> S) -> ~T & S)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..f716ab811e4c227bdc01ebd45496537393da6083 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(E <-> P) <-> ~F" + }, + { + "id": "F02", + "formula": "((~J & P) | ~E) & (J | E <-> P | ~J)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..6a963a54a8584ba11d72b7d730c2ab6092e76558 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~F | (~P -> J)", + "right": "F -> ~P -> J" + }, + { + "id": "PAIR02", + "left": "(J <-> F | E) & ~J | ~E", + "right": "(J <-> F | E) & (~J | ~E)" + }, + { + "id": "PAIR03", + "left": "(~(F -> ~P) <-> J & ~F) -> (~P & ~F) & (J & E)", + "right": "(F & P <-> (J & ~F)) -> (~P & ~F & (J & E))" + }, + { + "id": "PAIR04", + "left": "(E & ~P -> P -> E) & ((E <-> P) | (E | ~J))", + "right": "((E & ~P) -> ~P | E) & ((E <-> P) | ~(~E & J))" + }, + { + "id": "PAIR05", + "left": "(P <-> ~E) -> ~F <-> (~J -> ~P) & (~F | E)", + "right": "(P <-> ~E) -> ~F <-> (((~J -> ~P) & ~F) | E)" + }, + { + "id": "PAIR06", + "left": "(P & (J -> ~E)) | ~~(~F & E)", + "right": "(P & (J -> ~E)) | ~(F -> E)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a96f7958ca9fad2829fcee69236dce225d5ada4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 31 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f3a605af8ef9756edb06b38b1ef4d2e6b5d03d95 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(J <-> F | E) & ~J | ~E", + "right": "(J <-> F | E) & (~J | ~E)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(P <-> ~E) -> ~F <-> (~J -> ~P) & (~F | E)", + "right": "(P <-> ~E) -> ~F <-> (((~J -> ~P) & ~F) | E)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "(P & (J -> ~E)) | ~~(~F & E)", + "right": "(P & (J -> ~E)) | ~(F -> E)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR04" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(E <-> P) <-> ~F", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "((~J & P) | ~E) & (J | E <-> P | ~J)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0031/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..7d5d34a31a83734819f7cb9caf6072c16d0862f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(B -> A) -> B & R" + }, + { + "id": "F02", + "formula": "(T -> R) -> ~B <-> (~T -> ~R)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..8da0a5f4859a0d6ca68ab8f36e296290487228e2 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "A & R & (~R -> ~A) | ~T", + "right": "~(~A | ~R) & (~R -> ~A) | ~T" + }, + { + "id": "PAIR02", + "left": "A & (~B & R | (R -> B))", + "right": "A & (~(~B & R) -> ~(~R & B))" + }, + { + "id": "PAIR03", + "left": "B | ~(~R & A)", + "right": "B | (R | A)" + }, + { + "id": "PAIR04", + "left": "(~T -> A) -> (~R & B) | (B -> T)", + "right": "(~T -> A) -> ~R & B | (T -> B)" + }, + { + "id": "PAIR05", + "left": "~~(~T | A) & B", + "right": "(T -> A) & B" + }, + { + "id": "PAIR06", + "left": "~(B -> A) -> ~(~R & ~A)", + "right": "~R & ~A -> B -> A" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2022e43afbe3dfd884c57d22265569c6d6187ed7 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 40 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bef36a797c07c8192add0767b0a564963da6d79b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "A & (~B & R | (R -> B))", + "right": "A & (~(~B & R) -> ~(~R & B))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "B | ~(~R & A)", + "right": "B | (R | A)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(~T -> A) -> (~R & B) | (B -> T)", + "right": "(~T -> A) -> ~R & B | (T -> B)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR05", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(B -> A) -> B & R", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(T -> R) -> ~B <-> (~T -> ~R)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0040/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..b7992bed163bec927e24e4a1f99e542e8becf0bf --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(M -> G <-> M -> A) -> (G -> ~A) | G & ~A" + }, + { + "id": "F02", + "formula": "(F -> G & ~M) <-> (G | M) & F" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..c9bc50d3437879f1be3b8a9ef5a0bbb2c1f62e7a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~M -> (F | A)", + "right": "~~(~F & ~A) -> M" + }, + { + "id": "PAIR02", + "left": "(A | M) & (A | G)", + "right": "~(~((A | M) & A) & ~G)" + }, + { + "id": "PAIR03", + "left": "~(~M & ~G | A)", + "right": "(M -> ~G) & ~A" + }, + { + "id": "PAIR04", + "left": "A & ((~G -> F) & (F -> M))", + "right": "A & ((G | F) & (F -> M))" + }, + { + "id": "PAIR05", + "left": "~G <-> ~(~M & ~F | M & ~F)", + "right": "G <-> ~M <-> ~F" + }, + { + "id": "PAIR06", + "left": "((G -> ~A) | (~M | F)) -> (M -> A) | M & A", + "right": "((G -> ~A) -> ((M -> A) | M & A)) & (~M | F -> ~(M -> A) -> M & A)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7716600094eebf08c755c7a964a7850f4684b09f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 49 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..181595f46a7332e390fa21af6127ca9f0950e902 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(A | M) & (A | G)", + "right": "~(~((A | M) & A) & ~G)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(~M & ~G | A)", + "right": "(M -> ~G) & ~A" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~G <-> ~(~M & ~F | M & ~F)", + "right": "G <-> ~M <-> ~F" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR04", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(M -> G <-> M -> A) -> (G -> ~A) | G & ~A", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(F -> G & ~M) <-> (G | M) & F", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0049/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..028fb21ffa62cad419024f817dcef6cc117ac4e1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(P -> ~K) & (K -> P) | ~E" + }, + { + "id": "F02", + "formula": "(~E <-> ~K) & (~E -> P)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..5fe50a3318f678a855493dd56b04347a6dcc007c --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~P -> ~T -> (~E <-> ~K)", + "right": "~P & ~T -> (~E <-> ~K)" + }, + { + "id": "PAIR02", + "left": "(P & E | ~K) & (P & E | E) -> ~(T -> K) -> ~P", + "right": "P & E | ~K & E -> P -> T -> K" + }, + { + "id": "PAIR03", + "left": "~(K & E) -> P", + "right": "(K & E) -> ~P" + }, + { + "id": "PAIR04", + "left": "T | (E -> ~K)", + "right": "T & (E -> ~K)" + }, + { + "id": "PAIR05", + "left": "(K | T) & (T <-> E)", + "right": "(K | T) & (~E -> ~T)" + }, + { + "id": "PAIR06", + "left": "E & ~T -> (K | T)", + "right": "~(E & ~T) | (~K -> T)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f4bac37ed4c1ce45bc1e2eeb83223b1e23387e7 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 58 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3c70cf2c438802291c99739789596af9e9602d7e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(K & E) -> P", + "right": "(K & E) -> ~P" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "T | (E -> ~K)", + "right": "T & (E -> ~K)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(K | T) & (T <-> E)", + "right": "(K | T) & (~E -> ~T)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(P -> ~K) & (K -> P) | ~E", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(~E <-> ~K) & (~E -> P)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0058/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..4ab9dfc8ba11eb28c5533dc6f974ff891d7df51f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(A <-> G) <-> (G -> F)" + }, + { + "id": "F02", + "formula": "(F -> H) & (~F | ~G)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..fb637ea39af989c54d64a2542a47bea15f94d1ef --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~F | A -> (A | F) & ~G", + "right": "~(~F | A) | ~(~A & F) & ~G" + }, + { + "id": "PAIR02", + "left": "F & ~A | (F -> G) & (G -> F)", + "right": "F & ~A | (F <-> G)" + }, + { + "id": "PAIR03", + "left": "((~A | G) -> ~F -> H) | ~(~A | F)", + "right": "(~A | G <-> ~F -> H) | ~(A -> F)" + }, + { + "id": "PAIR04", + "left": "~(~(A -> G <-> ~F) | ~(F & G))", + "right": "(A -> G <-> ~F) & ~(F & G)" + }, + { + "id": "PAIR05", + "left": "~A | (H -> F)", + "right": "~A | (~H | F)" + }, + { + "id": "PAIR06", + "left": "(~G -> ~F) | ~H <-> A -> G", + "right": "~((F -> G) | ~H) <-> ~(A -> G)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01acf0db0f184bc30bc3284a000a3ced45c18f06 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 67 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..426dab32daeb8b7ef0d147c32ffb361f9d6de1ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "~F | A -> (A | F) & ~G", + "right": "~(~F | A) | ~(~A & F) & ~G" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "((~A | G) -> ~F -> H) | ~(~A | F)", + "right": "(~A | G <-> ~F -> H) | ~(A -> F)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~(~(A -> G <-> ~F) | ~(F & G))", + "right": "(A -> G <-> ~F) & ~(F & G)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR05", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(A <-> G) <-> (G -> F)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(F -> H) & (~F | ~G)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0067/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..43d9ddb6f44ce6b60f97f9a458fa601bb2527895 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~(L | J) <-> (M -> J)" + }, + { + "id": "F02", + "formula": "F -> (~L <-> ~J)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..549db188518078707a9f2a6d1b1b62ebedda7271 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "((L -> J) -> ~J & F) | ((F -> J) -> ~J & F)", + "right": "(L -> J) | (F -> J) -> ~J & F" + }, + { + "id": "PAIR02", + "left": "(M -> F) & (~F | M) & J", + "right": "(M <-> F) & J" + }, + { + "id": "PAIR03", + "left": "~(~(F | L) & (~L <-> M))", + "right": "F | L | (~L <-> M)" + }, + { + "id": "PAIR04", + "left": "(L -> J) | (F -> J) -> ~M & F | (L | M)", + "right": "(~(L -> J) -> (F -> J)) -> ~(~M & F) -> (L | M)" + }, + { + "id": "PAIR05", + "left": "~(M | L) -> J", + "right": "(M | L) & J" + }, + { + "id": "PAIR06", + "left": "F & ~L | ~~(~M -> J & F)", + "right": "F & ~L | (~M -> J & F)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/instruction.md b/tasks/argument-check/argument-check-equivalence-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29041bbb6738dd05003d9d34d5885adab3743a5d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/instruction.md @@ -0,0 +1,15 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/task.toml b/tasks/argument-check/argument-check-equivalence-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f22017d630155a5139834df28a3f6ccc1fbfdba2 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 76 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..10560a7ed356082bde028aefc5b95f7b652e826e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/checks.json @@ -0,0 +1,171 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "((L -> J) -> ~J & F) | ((F -> J) -> ~J & F)", + "right": "(L -> J) | (F -> J) -> ~J & F" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(~(F | L) & (~L <-> M))", + "right": "F | L | (~L <-> M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~(M | L) -> J", + "right": "(M | L) & J" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR02", + "PAIR04", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~(L | J) <-> (M -> J)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "F -> (~L <-> ~J)", + "form": "cnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d2-t0076/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..046cf1b0875fde0cd168627ad10e83a510345188 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "F & H & (L & S -> ~H)" + }, + { + "id": "F02", + "formula": "L | S <-> (M <-> ~F) & (M | L)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..95d1240998acf9b742d09673c3d27fb69d4ea6f1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(M|(F->H))->~P|(~H|~F)", + "right": "~(~M & (F -> H)) -> ~P | (~H | ~F)" + }, + { + "id": "PAIR02", + "left": "~(~S | M) <-> ~(~F & L)", + "right": "(S & ~M) <-> F | L" + }, + { + "id": "PAIR03", + "left": "~L -> ~S <-> M & ~L & (H <-> L)", + "right": "~L->~S<->~(~M|L)&(H&L|~H&~L)" + }, + { + "id": "PAIR04", + "left": "F | P -> ((~L -> M) & (~P & ~L))", + "right": "F | P -> (L | M) & ~(~P -> L)" + }, + { + "id": "PAIR05", + "left": "P & H -> S & ~M | ~S & ~M", + "right": "(P & H) -> (S <-> ~M)" + }, + { + "id": "PAIR06", + "left": "L&~H&(~L|M)->(~(H->~S)&~L)", + "right": "L & ~H & (L -> M) -> H & S & ~L" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/task.toml b/tasks/argument-check/argument-check-equivalence-d3-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..51b37439bffc2e0694e3c5943fe20d80765aac95 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10007 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0dcb4f29d514cde4a9cc190d5779540700032a41 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "left-entails-right", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(M|(F->H))->~P|(~H|~F)", + "right": "~(~M & (F -> H)) -> ~P | (~H | ~F)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "~(~S | M) <-> ~(~F & L)", + "right": "(S & ~M) <-> F | L" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "P & H -> S & ~M | ~S & ~M", + "right": "(P & H) -> (S <-> ~M)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR03", + "PAIR04", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "F & H & (L & S -> ~H)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "L | S <-> (M <-> ~F) & (M | L)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "F & H & (L & S -> ~H)", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "L | S <-> (M <-> ~F) & (M | L)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..7d6c20b7e94ca9120172805322af577c3a008e78 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(T & (R | Q)) & (~J | T <-> Q & T)" + }, + { + "id": "F02", + "formula": "(Q->J)->(S<->R)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..97995feb6852f309acac85372b9dfc144398e64e --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~(D->~Q)&(S&~R)<->S|(T->Q)", + "right": "(D & Q & (S & ~R)) <-> S | (T -> Q)" + }, + { + "id": "PAIR02", + "left": "(R <-> (J -> S) & (~S -> J)) -> (D <-> J) & (~S -> J)", + "right": "(R<->J<->S)->(D<->J)&(~S->J)" + }, + { + "id": "PAIR03", + "left": "~((R|S)&(~Q|D))->~(D|T|(D->J))", + "right": "D | T | (D -> J) -> (R | S) & (~Q | D)" + }, + { + "id": "PAIR04", + "left": "(~J <-> ~D | ~Q) & ((D -> S) & ~Q)", + "right": "(~J <-> ~D | ~Q) & ((~D -> ~S) & ~Q)" + }, + { + "id": "PAIR05", + "left": "~Q & T & (~D & ~S)", + "right": "~(~Q & T -> D | S)" + }, + { + "id": "PAIR06", + "left": "~(Q&S)<->T->J", + "right": "Q & S <-> T -> J" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-e0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/task.toml b/tasks/argument-check/argument-check-equivalence-d3-e0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ddea77281755628cc7662943d0cbff59a294321 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "eval"] +isced_f = "0223" +family = "equivalence" +split = "eval" +seed = 10016 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..39087d7c1d20d21750d3da062e75b6ba6af6f14a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(R <-> (J -> S) & (~S -> J)) -> (D <-> J) & (~S -> J)", + "right": "(R<->J<->S)->(D<->J)&(~S->J)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(~J <-> ~D | ~Q) & ((D -> S) & ~Q)", + "right": "(~J <-> ~D | ~Q) & ((~D -> ~S) & ~Q)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "~(Q&S)<->T->J", + "right": "Q & S <-> T -> J" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(T & (R | Q)) & (~J | T <-> Q & T)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(Q->J)->(S<->R)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(T & (R | Q)) & (~J | T <-> Q & T)", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(Q->J)->(S<->R)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-e0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..d5f97ee5da217f295a25e43f97483e5e5f8443e4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "P & (M -> ~N) <-> (M -> ~J) | J & P" + }, + { + "id": "F02", + "formula": "N & (L | (~M -> ~C))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..1fd85e8a9bb3f36acbbbace47b4e3b4b4f94d1dd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "~L & C & (~P -> ~J)", + "right": "~(L | C) & (~P -> ~J)" + }, + { + "id": "PAIR02", + "left": "~(C | M <-> L | P)", + "right": "~((~C -> M) <-> ~(~L & P))" + }, + { + "id": "PAIR03", + "left": "(L | ~P) -> C | N -> P | C", + "right": "L | ~P -> (C | N -> ~P -> C)" + }, + { + "id": "PAIR04", + "left": "~(~(M -> P) & ~(M -> N)) & (~M & (C | N))", + "right": "((M -> P) | (M -> N)) & (~M & (C | N))" + }, + { + "id": "PAIR05", + "left": "~(J <-> L) | (N -> ~(~M -> ~L))", + "right": "(J <-> L) -> ((~M -> ~L) -> ~N)" + }, + { + "id": "PAIR06", + "left": "J | M -> L | J <-> C & J", + "right": "((J -> L | J) | (M -> L | J)) <-> C & J" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c24ce92855fe5e740cc75dd4d8ae00674f69985c --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 7 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a866c11908a753168e1bcf90b66629b0d7651bac --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "~L & C & (~P -> ~J)", + "right": "~(L | C) & (~P -> ~J)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "~(C | M <-> L | P)", + "right": "~((~C -> M) <-> ~(~L & P))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "right-entails-left", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "J | M -> L | J <-> C & J", + "right": "((J -> L | J) | (M -> L | J)) <-> C & J" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR03", + "PAIR04", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "P & (M -> ~N) <-> (M -> ~J) | J & P", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "N & (L | (~M -> ~C))", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "P & (M -> ~N) <-> (M -> ~J) | J & P", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "N & (L | (~M -> ~C))", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..0eeb180fa6ef889c3a86b4fd233a8dbcfa4d8b0a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~S | T <-> (N & (E | T))" + }, + { + "id": "F02", + "formula": "(~N <-> ~L | ~F) -> S | N" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..27207941b6529f1cee1ac5d673a96da12eeb50c1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(~S & ~N & F) | ~S & ~N & ~S <-> ~~(~N & L)", + "right": "~S & ~N & (F | ~S) <-> ~(N | ~L)" + }, + { + "id": "PAIR02", + "left": "(E | F <-> ~N <-> L) <-> T | ~N | (N | F)", + "right": "(E | F <-> (~N <-> L)) <-> (~T -> ~N) | (N | F)" + }, + { + "id": "PAIR03", + "left": "(E -> F) & ~(~L & N) <-> ~T", + "right": "(E->F)&(~L->N)<->~T" + }, + { + "id": "PAIR04", + "left": "N -> (L -> ~T) | F", + "right": "N -> ~(L & T) | F" + }, + { + "id": "PAIR05", + "left": "(~(~L -> T) | (T | F)) & ((L | N) -> F)", + "right": "(~L & T | (T | F)) & (L | N -> F)" + }, + { + "id": "PAIR06", + "left": "~S & (E <-> ~L <-> N)", + "right": "~S & (E <-> (~L -> N) & (~N -> ~L))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f7bf73f63d16207c8703b507016d2c9b869b1f5 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 16 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1527cce09b8998913d53fbf6566b58275ac8b6f4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "(E -> F) & ~(~L & N) <-> ~T", + "right": "(E->F)&(~L->N)<->~T" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "right-entails-left", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(~(~L -> T) | (T | F)) & ((L | N) -> F)", + "right": "(~L & T | (T | F)) & (L | N -> F)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "~S & (E <-> ~L <-> N)", + "right": "~S & (E <-> (~L -> N) & (~N -> ~L))" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02", + "PAIR04" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~S | T <-> (N & (E | T))", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(~N <-> ~L | ~F) -> S | N", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~S | T <-> (N & (E | T))", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(~N <-> ~L | ~F) -> S | N", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..2057ecba5406bd26cc90fd439dfc061050a8d550 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~((~M -> R) & (~L -> S))" + }, + { + "id": "F02", + "formula": "(R|~L|~S)&(R&~M<->R|~M)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..7c16bbf64ae3ca1d85d9224b79e5ed3a18a5ab52 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "((K -> S) | M & S) & (R & H)", + "right": "((K -> S) | M & S) & ~(~R | ~H)" + }, + { + "id": "PAIR02", + "left": "(K | ~(~M & ~S)) & ~(~L | M)", + "right": "(K | (M | S)) & ~(~L | M)" + }, + { + "id": "PAIR03", + "left": "~(~(~K -> L) | ((R -> K) -> S | ~R))", + "right": "(~K -> L) & ((R -> K) -> (S | ~R))" + }, + { + "id": "PAIR04", + "left": "(~S | R) & ((~H -> L) -> (M <-> H))", + "right": "(~S | R) & ((~H -> L) -> M & H | ~M & H)" + }, + { + "id": "PAIR05", + "left": "R|~L<->S->H", + "right": "R | ~L <-> S | ~H" + }, + { + "id": "PAIR06", + "left": "(L <-> S -> R) & (S & H -> R | L)", + "right": "(L <-> S -> R) & (~(~S | ~H) -> (R | L))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..299493a7b1b7c7ace1143ed1f4a344fc5ffbc717 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 25 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..241359f2af5db6b74db8ef197ca7dfc9b47d67a1 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~(~(~K -> L) | ((R -> K) -> S | ~R))", + "right": "(~K -> L) & ((R -> K) -> (S | ~R))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(~S | R) & ((~H -> L) -> (M <-> H))", + "right": "(~S | R) & ((~H -> L) -> M & H | ~M & H)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "R|~L<->S->H", + "right": "R | ~L <-> S | ~H" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~((~M -> R) & (~L -> S))", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(R|~L|~S)&(R&~M<->R|~M)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~((~M -> R) & (~L -> S))", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(R|~L|~S)&(R&~M<->R|~M)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0025/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..cfae12edb9a94b62f9e3b45746bb2e9bcda35a9b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "~((~E<->R)|(~T|F))" + }, + { + "id": "F02", + "formula": "~D & ~T <-> ~P -> F" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..9780f86e42554c1003a0596de292bae62ea97241 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "((E | F) <-> T | ~R) & ((E <-> T) -> R -> ~E)", + "right": "(~E -> F <-> T | ~R) & ((E <-> T) -> E -> ~R)" + }, + { + "id": "PAIR02", + "left": "~(F & E) & (~T -> D)", + "right": "(~F | E) & (T | D)" + }, + { + "id": "PAIR03", + "left": "~(~P | ~F) -> ~(D & R)", + "right": "(P->~F)|~(D&R)" + }, + { + "id": "PAIR04", + "left": "(~P -> ~E) | E & (R -> T)", + "right": "(~P -> ~E) | (E & (R | T))" + }, + { + "id": "PAIR05", + "left": "(T -> P -> R) & ~(~F -> ~R)", + "right": "((T & P) -> R) & (~F & R)" + }, + { + "id": "PAIR06", + "left": "(E -> ~F) | P -> (F <-> D)", + "right": "(E <-> ~F) | P -> (F <-> D)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e02c27117e11be53a38a0b3057485df2ff3ec6f --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 34 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cfa7bb88896eb8218d3d0ed0cf2fe24e3e87fdbe --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "~(F & E) & (~T -> D)", + "right": "(~F | E) & (T | D)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(~P -> ~E) | E & (R -> T)", + "right": "(~P -> ~E) | (E & (R | T))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "left-entails-right", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "(E -> ~F) | P -> (F <-> D)", + "right": "(E <-> ~F) | P -> (F <-> D)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR03", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~((~E<->R)|(~T|F))", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "~D & ~T <-> ~P -> F", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "~((~E<->R)|(~T|F))", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "~D & ~T <-> ~P -> F", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0034/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..bb2deed66b0a77014e3c6813e816659ccf8b8d0a --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "Q & C -> L & C <-> S" + }, + { + "id": "F02", + "formula": "T | L <-> ~E -> C" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..b10c17cdba38bb9013c7e83caeba25ecac988783 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "((C | Q) -> Q & ~S) -> (E & (Q | S))", + "right": "~(E & (Q | S)) -> ~(~(C | Q) | (Q & ~S))" + }, + { + "id": "PAIR02", + "left": "S & L & (E -> L) & ((E <-> S) | (E <-> Q))", + "right": "~(S & L -> ~(E -> L)) & ((E <-> S) | (E & Q | ~E & Q))" + }, + { + "id": "PAIR03", + "left": "~E & ~(~S | ~L) | ~(Q & ~(T <-> C))", + "right": "~E & (S & ~L) | (Q -> (T <-> C))" + }, + { + "id": "PAIR04", + "left": "((Q -> ~L) | T) -> ~(E -> C)", + "right": "((Q -> ~L) -> ~(E -> C)) & (T -> ~(E -> C))" + }, + { + "id": "PAIR05", + "left": "~C&S|(~(~T&E)<->L)", + "right": "~C&S|(T|E<->L)" + }, + { + "id": "PAIR06", + "left": "E & ~Q & (~S | L) & ((~T <-> ~E) | (L -> E))", + "right": "E & ~Q & (S -> L) & ((T <-> E) | (L -> E))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7a99673124514db8f8567d5df057227f747da3cf --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 43 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..fc78644a1239a2b413405ff997eef0082ef545cb --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "S & L & (E -> L) & ((E <-> S) | (E <-> Q))", + "right": "~(S & L -> ~(E -> L)) & ((E <-> S) | (E & Q | ~E & Q))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 50, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 50, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR03", + "left": "~E & ~(~S | ~L) | ~(Q & ~(T <-> C))", + "right": "~E & (S & ~L) | (Q -> (T <-> C))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "~C&S|(~(~T&E)<->L)", + "right": "~C&S|(T|E<->L)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR04", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "Q & C -> L & C <-> S", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "T | L <-> ~E -> C", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "Q & C -> L & C <-> S", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "T | L <-> ~E -> C", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0043/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..ef03e2d8e2913da5559dddfca1f1a59e61473be4 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "L | P -> ~P & T & S" + }, + { + "id": "F02", + "formula": "(L->R<->~P)->(~K<->~R->L)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..3c12130adee60a81e5de36911344ef0854706b55 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(T <-> ~S) & (P -> (L <-> R))", + "right": "(T <-> ~S) & (P -> ~(L & ~R))" + }, + { + "id": "PAIR02", + "left": "~(~L & (R <-> ~S)) <-> (~R & (S | ~T))", + "right": "L -> (R <-> ~S) <-> ~R & (~S -> ~T)" + }, + { + "id": "PAIR03", + "left": "~R | ~K | ((P | ~S) | (~L -> ~S))", + "right": "R & K -> P | ~S | (~L -> ~S)" + }, + { + "id": "PAIR04", + "left": "T|P->((~L->R)&S)", + "right": "T | P -> (L | R) & S" + }, + { + "id": "PAIR05", + "left": "(~(~K & R) -> ~(~T & K)) & ~(~R <-> P)", + "right": "(~T & K -> (~K & R)) & ~(~R <-> P)" + }, + { + "id": "PAIR06", + "left": "~(~S & L) & ((P <-> S) & ~(~R | S))", + "right": "(S|~L)&((P<->S)&(R&S))" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f18c6d4868ef4781b96d0fea5654435552b50d0d --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 52 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a3c8b13c52b756d02fb01e04f41e34c4f601305b --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "left-entails-right", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(T <-> ~S) & (P -> (L <-> R))", + "right": "(T <-> ~S) & (P -> ~(L & ~R))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "~(~L & (R <-> ~S)) <-> (~R & (S | ~T))", + "right": "L -> (R <-> ~S) <-> ~R & (~S -> ~T)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "~(~S & L) & ((P <-> S) & ~(~R | S))", + "right": "(S|~L)&((P<->S)&(R&S))" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR03", + "PAIR04", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "L | P -> ~P & T & S", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(L->R<->~P)->(~K<->~R->L)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "L | P -> ~P & T & S", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(L->R<->~P)->(~K<->~R->L)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0052/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..e3333fd6a7cef3a0c7a71f30c2d1552647a973cb --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "((E|M)->M|E)->(A|K<->A|~E)" + }, + { + "id": "F02", + "formula": "(M <-> ~R) & E & ((A -> ~M) | ~R)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..9c1f2f6fcd7df69d17d5329cb985d877aa9efeff --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(~K | A) & (Q -> ~K) & (~R & ~Q)", + "right": "(~K | A) & (~Q | ~K) & ~(R | Q)" + }, + { + "id": "PAIR02", + "left": "(Q&A|A)&(Q&A|(R|M))", + "right": "~(Q & A) -> (A & (R | M))" + }, + { + "id": "PAIR03", + "left": "(Q|A)->(R->~K)<->(~M->E)&~Q", + "right": "Q | A -> (R -> ~K) <-> (E | M) & ~Q" + }, + { + "id": "PAIR04", + "left": "(Q<->M)->~R->Q<->Q->~E->~R", + "right": "(Q <-> M) -> ~R -> Q <-> Q | (R -> E)" + }, + { + "id": "PAIR05", + "left": "(~K <-> A) | ((R -> ~K) | A & E)", + "right": "(~K <-> A) | ((R | K) | A & E)" + }, + { + "id": "PAIR06", + "left": "~((~M -> ~E) -> A & R) -> ~(~E -> R & M)", + "right": "((~M -> ~E) -> (A & R)) -> ~E -> R & M" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c3d07fa88c7096d4c589b8b99b01a445f15b907 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 61 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..57462c7709c2389be14a01f462d129dbc6d84475 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "(Q<->M)->~R->Q<->Q->~E->~R", + "right": "(Q <-> M) -> ~R -> Q <-> Q | (R -> E)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR05", + "left": "(~K <-> A) | ((R -> ~K) | A & E)", + "right": "(~K <-> A) | ((R | K) | A & E)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "~((~M -> ~E) -> A & R) -> ~(~E -> R & M)", + "right": "((~M -> ~E) -> (A & R)) -> ~E -> R & M" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR01", + "PAIR02", + "PAIR03" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "((E|M)->M|E)->(A|K<->A|~E)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(M <-> ~R) & E & ((A -> ~M) | ~R)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "((E|M)->M|E)->(A|K<->A|~E)", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(M <-> ~R) & E & ((A -> ~M) | ~R)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0061/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..600ebd38b811da17003a869e6aee9f01b8fafe09 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(~R -> Q) & (G & R) | (B | ~R)" + }, + { + "id": "F02", + "formula": "B | K -> (~R | ~Q)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..5a4d399fc6669dc6083221454dd6ea0e9a8b4ebf --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(B->~C)&(Q<->~C)<->~C|B|R&~Q", + "right": "~(~C & ~B) & (Q <-> ~C) <-> (~C | B | R & ~Q)" + }, + { + "id": "PAIR02", + "left": "~((R->C)|(Q|K))", + "right": "~((~R->~C)|(~Q->K))" + }, + { + "id": "PAIR03", + "left": "((R | B) | C) & (G -> ~C <-> G -> B)", + "right": "(R | B | C) & (C -> ~G <-> G -> B)" + }, + { + "id": "PAIR04", + "left": "~Q|B|~C&K", + "right": "~Q | B | C & ~K" + }, + { + "id": "PAIR05", + "left": "(K | B) & ((Q <-> G) & (G <-> C))", + "right": "(K | B) & ~(~(Q <-> G) | ~(G <-> C))" + }, + { + "id": "PAIR06", + "left": "(~(~C -> ~K) | B) & (~(G & C) -> ~(B | C))", + "right": "((~C -> ~K) -> B) & (B | C -> G & C)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0070/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7da4af5fd8ab703cfe7fe36778fb72fd6e5afca0 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 70 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1722d0be2814c9077b61e7e749617da245c73c60 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(B->~C)&(Q<->~C)<->~C|B|R&~Q", + "right": "~(~C & ~B) & (Q <-> ~C) <-> (~C | B | R & ~Q)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "~((R->C)|(Q|K))", + "right": "~((~R->~C)|(~Q->K))" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR04", + "left": "~Q|B|~C&K", + "right": "~Q | B | C & ~K" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR03", + "PAIR05", + "PAIR06" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(~R -> Q) & (G & R) | (B | ~R)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "B | K -> (~R | ~Q)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(~R -> Q) & (G & R) | (B | ~R)", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "B | K -> (~R | ~Q)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0070/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/Dockerfile b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/convert.json b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/convert.json new file mode 100644 index 0000000000000000000000000000000000000000..ee54aea4d71df65bc6149b12c45942a8dc2bb571 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/convert.json @@ -0,0 +1,10 @@ +[ + { + "id": "F01", + "formula": "(A | M | (~M -> Q)) -> ~J" + }, + { + "id": "F02", + "formula": "(A->B|D)->~(A<->M)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/pairs.json b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/pairs.json new file mode 100644 index 0000000000000000000000000000000000000000..dad6a9d65b442111a491fe1e0ef5411b27df67ec --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/environment/workdir/pairs.json @@ -0,0 +1,32 @@ +[ + { + "id": "PAIR01", + "left": "(J -> M | D) & (Q & J -> M & J)", + "right": "((M|D)->J)&((Q&J)->M&J)" + }, + { + "id": "PAIR02", + "left": "(B&A)|(M->~B)->(~J->M)->B->~J", + "right": "B & A | (M -> ~B) -> ~J | ~M -> ~(B & J)" + }, + { + "id": "PAIR03", + "left": "(B|D|(Q|~A))&~(~(Q<->B)&~(D<->B))", + "right": "((B | D) | (Q | ~A)) & ((Q <-> B) | (D <-> B))" + }, + { + "id": "PAIR04", + "left": "J&B|(~B<->~A)<->M->Q&A", + "right": "J & B | (B <-> A) <-> (M -> Q & A)" + }, + { + "id": "PAIR05", + "left": "~(Q&~B)|(~Q|~(~M|~A))", + "right": "~Q | B | (~Q | (M & A))" + }, + { + "id": "PAIR06", + "left": "((B&~J)<->~(A&~J))<->(A->J)|(J->~D)", + "right": "((B & ~J) <-> (A -> J)) <-> (A -> J) | (~J -> D)" + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/instruction.md b/tasks/argument-check/argument-check-equivalence-d3-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43fff35318a7493ecc3e0f49a9d877fe46853872 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/instruction.md @@ -0,0 +1,18 @@ +# Argument check: equivalence + +`pairs.json` holds 6 pairs of formulas in propositional logic, `left` and `right`. `convert.json` holds 2 further formulas to rewrite in normal form. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Compare the two formulas of every pair with a full truth table over the atoms that occur in either of them. + +Write `answer.json` in this folder, a JSON object with: + +- `pairs`: an object keyed by pair id. For each pair give + - `equivalent`: `true` or `false`. + - `left_models`: the number of rows in which `left` is true, as an integer. + - `right_models`: the number of rows in which `right` is true, as an integer. + - `left_only_rows`: the number of rows in which `left` is true and `right` is false, as an integer. + - `relation`: one of `equivalent`, `left-entails-right` (not equivalent, and `right` is true in every row in which `left` is true), `right-entails-left` (not equivalent, and `left` is true in every row in which `right` is true) or `neither`. + - `distinguishing`: for a pair that is not equivalent, one distinguishing valuation (an object giving `true` or `false` to exactly the atoms that occur in the pair). Any row in which the two formulas differ is accepted. For an equivalent pair give `null`. +- `equivalent_ids`: list of the ids of the equivalent pairs (any order). +- `cnf`: an object keyed by the ids in `convert.json`. Each value is a string: a formula in the syntax of the reference that is in conjunctive normal form, is equivalent to the given formula and uses no atom that the given formula does not contain. Any such formula of at most 2000 characters is accepted. +- `dnf`: the same for disjunctive normal form. diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/oracle.py b/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/solve.sh b/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/task.toml b/tasks/argument-check/argument-check-equivalence-d3-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..87f961de263c6cd2fed77727f0b79eda56f0a945 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "equivalence", "isced-0223", "train"] +isced_f = "0223" +family = "equivalence" +split = "train" +seed = 79 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/checks.json b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b587bbd598ad712a80a4dd745eba3ff6ff9596a0 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "pairs.PAIR01.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.right_models", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.left_only_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "pairs.PAIR01.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR01", + "left": "(J -> M | D) & (Q & J -> M & J)", + "right": "((M|D)->J)&((Q&J)->M&J)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.right_models", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR02.relation", + "type": "str", + "value": "left-entails-right", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR02", + "left": "(B&A)|(M->~B)->(~J->M)->B->~J", + "right": "B & A | (M -> ~B) -> ~J | ~M -> ~(B & J)" + }, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.right_models", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR03.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.right_models", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR04.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.equivalent", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.right_models", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.left_only_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "pairs.PAIR05.relation", + "type": "str", + "value": "equivalent", + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.equivalent", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.right_models", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.left_only_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "pairs.PAIR06.relation", + "type": "str", + "value": "neither", + "weight": 1.0 + }, + { + "type": "custom", + "name": "distinguishing_valuation", + "args": { + "id": "PAIR06", + "left": "((B&~J)<->~(A&~J))<->(A->J)|(J->~D)", + "right": "((B & ~J) <-> (A -> J)) <-> (A -> J) | (~J -> D)" + }, + "weight": 1.0 + }, + { + "path": "equivalent_ids", + "type": "set", + "value": [ + "PAIR03", + "PAIR04", + "PAIR05" + ], + "item": "str", + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(A | M | (~M -> Q)) -> ~J", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(A->B|D)->~(A<->M)", + "form": "cnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F01", + "formula": "(A | M | (~M -> Q)) -> ~J", + "form": "dnf" + }, + "weight": 2 + }, + { + "type": "custom", + "name": "normal_form", + "args": { + "id": "F02", + "formula": "(A->B|D)->~(A<->M)", + "form": "dnf" + }, + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/test.sh b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/validators.py b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/verify.py b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-equivalence-d3-t0079/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..0d204747e127a82cdafc172b06cb41fcb5abdd65 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 12", + "premises": [ + "M", + "F -> M" + ], + "conclusion": "F" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 16", + "premises": [ + "M -> F", + "~F | T" + ], + "conclusion": "T -> M" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 5", + "premises": [ + "T | M", + "~M -> T" + ], + "conclusion": "T" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 19", + "premises": [ + "F", + "T & F" + ], + "conclusion": "T" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 7", + "premises": [ + "~M", + "~M & T" + ], + "conclusion": "T" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/instruction.md b/tasks/argument-check/argument-check-validity-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-e0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/task.toml b/tasks/argument-check/argument-check-validity-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4edcc140d676e3891bb4cfd15a320ca97397fe23 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10002 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-e0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c86b250855ee7820f450ec27dfc0141688664ea2 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "M", + "F -> M" + ], + "conclusion": "F" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "M -> F", + "~F | T" + ], + "conclusion": "T -> M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "T | M", + "~M -> T" + ], + "conclusion": "T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG04", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-e0002/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-e0002/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-e0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-e0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..7e3d38b135439c5559446aacd8cb399c6b980136 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 1, question 19", + "premises": [ + "D | T", + "B -> ~D" + ], + "conclusion": "T -> B" + }, + { + "id": "ARG02", + "source": "Sheet 8, question 12", + "premises": [ + "(~D & B) -> T", + "~T" + ], + "conclusion": "D" + }, + { + "id": "ARG03", + "source": "Sheet 5, question 20", + "premises": [ + "D -> T", + "D -> B" + ], + "conclusion": "T -> B" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 20", + "premises": [ + "T -> (~B -> D)", + "~B" + ], + "conclusion": "T -> D" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 4", + "premises": [ + "~T", + "D -> (T | B)" + ], + "conclusion": "D -> B" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/instruction.md b/tasks/argument-check/argument-check-validity-d1-e0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-e0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-e0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/task.toml b/tasks/argument-check/argument-check-validity-d1-e0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c795e06c7c1b30fd909d40ffb2185f0095a4a7d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10011 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-e0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..852cf92b98bd0ae9b7d6921abce82e6901023473 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "D | T", + "B -> ~D" + ], + "conclusion": "T -> B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "(~D & B) -> T", + "~T" + ], + "conclusion": "D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "D -> T", + "D -> B" + ], + "conclusion": "T -> B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG04", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-e0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-e0011/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-e0011/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-e0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-e0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..bd8619fe1039fa502aadd69fd16613281ebf97dc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 8, question 2", + "premises": [ + "~S -> M", + "~S -> ~M" + ], + "conclusion": "S" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 16", + "premises": [ + "M", + "~(M & S)" + ], + "conclusion": "~S" + }, + { + "id": "ARG03", + "source": "Sheet 1, question 18", + "premises": [ + "E -> ~M", + "E -> M" + ], + "conclusion": "~E" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 4", + "premises": [ + "M -> E", + "E" + ], + "conclusion": "M" + }, + { + "id": "ARG05", + "source": "Sheet 6, question 8", + "premises": [ + "S | E", + "S" + ], + "conclusion": "~E" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/instruction.md b/tasks/argument-check/argument-check-validity-d1-e0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-e0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-e0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/task.toml b/tasks/argument-check/argument-check-validity-d1-e0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..21d936e4258e2fd233b6eb4d7da3886444b2119e --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10020 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-e0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..251976b07db58758113e8dbf9bf4e66e113c4bdc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/tests/checks.json @@ -0,0 +1,129 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "M -> E", + "E" + ], + "conclusion": "M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "S | E", + "S" + ], + "conclusion": "~E" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-e0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-e0020/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-e0020/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-e0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-e0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..f1834e2fdd0d855c7d0c9695e0f27574d8701bea --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 3, question 18", + "premises": [ + "~G", + "~(~G & ~P)" + ], + "conclusion": "P" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 4", + "premises": [ + "~R", + "~(R & P)" + ], + "conclusion": "P" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 1", + "premises": [ + "G | R", + "G -> R" + ], + "conclusion": "G" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 3", + "premises": [ + "~R -> P", + "R -> ~G" + ], + "conclusion": "~G | P" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 20", + "premises": [ + "(G & ~R) -> P", + "G" + ], + "conclusion": "~R -> P" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/task.toml b/tasks/argument-check/argument-check-validity-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..889e8f5f98390203200704392d509e7693bba619 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 2 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..27b9e4111f2cb404d927786c4d0c894aeb02d6d3 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/tests/checks.json @@ -0,0 +1,129 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "~R", + "~(R & P)" + ], + "conclusion": "P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "G | R", + "G -> R" + ], + "conclusion": "G" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0002/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0002/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..f37c11fa6c7025b2bb3d2cf5aca960a057be1927 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 1, question 15", + "premises": [ + "T -> ~H", + "T -> H" + ], + "conclusion": "~T" + }, + { + "id": "ARG02", + "source": "Sheet 2, question 9", + "premises": [ + "~C <-> H", + "T <-> H" + ], + "conclusion": "~T | H" + }, + { + "id": "ARG03", + "source": "Sheet 4, question 11", + "premises": [ + "~(T & H)", + "~T" + ], + "conclusion": "H" + }, + { + "id": "ARG04", + "source": "Sheet 8, question 6", + "premises": [ + "H -> T", + "H | ~C" + ], + "conclusion": "T" + }, + { + "id": "ARG05", + "source": "Sheet 6, question 1", + "premises": [ + "~H -> C", + "T -> C" + ], + "conclusion": "T -> ~H" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/task.toml b/tasks/argument-check/argument-check-validity-d1-t0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff9a665c9afdb37784691c627fb5b0b3f62aeff1 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 11 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2587cb124058e0f454c053cf62b01ba813942d47 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~(T & H)", + "~T" + ], + "conclusion": "H" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "H -> T", + "H | ~C" + ], + "conclusion": "T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "~H -> C", + "T -> C" + ], + "conclusion": "T -> ~H" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0011/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0011/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..81ae4b2903bb9407887a052de306ef7faedbc07a --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 5", + "premises": [ + "J -> C", + "J -> ~C" + ], + "conclusion": "~J" + }, + { + "id": "ARG02", + "source": "Sheet 3, question 5", + "premises": [ + "~C | J", + "B -> C" + ], + "conclusion": "J -> B" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 12", + "premises": [ + "B -> (~J | ~C)", + "J" + ], + "conclusion": "B -> ~C" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 18", + "premises": [ + "B | C", + "B | ~C" + ], + "conclusion": "C" + }, + { + "id": "ARG05", + "source": "Sheet 7, question 14", + "premises": [ + "B | C", + "C <-> ~B" + ], + "conclusion": "B" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/task.toml b/tasks/argument-check/argument-check-validity-d1-t0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0066a3629798ac53b731fc3e0ce94f4d1e8be21b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 20 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..faafa7522e1320685b643573e40a9184f591d6d3 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "~C | J", + "B -> C" + ], + "conclusion": "J -> B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "B | C", + "B | ~C" + ], + "conclusion": "C" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "B | C", + "C <-> ~B" + ], + "conclusion": "B" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0020/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0020/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..112d7d16f2183569612ca49e04f0f8c177e3020b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 8", + "premises": [ + "~L", + "~(L & K)" + ], + "conclusion": "K" + }, + { + "id": "ARG02", + "source": "Sheet 2, question 10", + "premises": [ + "~N", + "N | K" + ], + "conclusion": "K" + }, + { + "id": "ARG03", + "source": "Sheet 4, question 16", + "premises": [ + "L -> ~K", + "L | N" + ], + "conclusion": "~K" + }, + { + "id": "ARG04", + "source": "Sheet 1, question 19", + "premises": [ + "~L <-> ~N", + "N -> K" + ], + "conclusion": "K" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 4", + "premises": [ + "~N", + "(~N & K) -> L" + ], + "conclusion": "K -> L" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0029/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/task.toml b/tasks/argument-check/argument-check-validity-d1-t0029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76c17753b2d2dfc3b76e04997dabe5da66b6829c --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 29 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0029/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2f043cf2c3958b3334d6fdfd328a024850b1c434 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "~L", + "~(L & K)" + ], + "conclusion": "K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "L -> ~K", + "L | N" + ], + "conclusion": "~K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "~L <-> ~N", + "N -> K" + ], + "conclusion": "K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0029/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0029/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0029/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0029/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..f9c5603b568748e0e5d9b3fc40dcc0304f11ff40 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 8, question 12", + "premises": [ + "A -> M", + "~E -> A" + ], + "conclusion": "~E -> M" + }, + { + "id": "ARG02", + "source": "Sheet 4, question 8", + "premises": [ + "~M", + "~M | ~A" + ], + "conclusion": "A" + }, + { + "id": "ARG03", + "source": "Sheet 5, question 18", + "premises": [ + "~A", + "~(A & M)" + ], + "conclusion": "M" + }, + { + "id": "ARG04", + "source": "Sheet 2, question 18", + "premises": [ + "A & E", + "E <-> ~M" + ], + "conclusion": "A -> ~M" + }, + { + "id": "ARG05", + "source": "Sheet 5, question 15", + "premises": [ + "~A <-> ~M", + "E & ~A" + ], + "conclusion": "A" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0038/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/task.toml b/tasks/argument-check/argument-check-validity-d1-t0038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f15c3f60239b9aa9fd44c1ccc7ae49816bb9219 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 38 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0038/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..436e72b6fbe70f760def631602f7aeaee21548dc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "~M", + "~M | ~A" + ], + "conclusion": "A" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~A", + "~(A & M)" + ], + "conclusion": "M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "~A <-> ~M", + "E & ~A" + ], + "conclusion": "A" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0038/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0038/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0038/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0038/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..2962882c453b2d2682fa5363bdadb92e2bf8accb --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 4, question 4", + "premises": [ + "J | K", + "~K" + ], + "conclusion": "J" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 12", + "premises": [ + "~J", + "~F -> J" + ], + "conclusion": "F" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 14", + "premises": [ + "K", + "~J -> K" + ], + "conclusion": "~J" + }, + { + "id": "ARG04", + "source": "Sheet 2, question 5", + "premises": [ + "J -> F", + "J -> K" + ], + "conclusion": "J -> (F & K)" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 14", + "premises": [ + "~F & J", + "K | J" + ], + "conclusion": "K" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0047/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/task.toml b/tasks/argument-check/argument-check-validity-d1-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..df6f95bcd928eeb95436843869813937d26995e8 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 47 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0047/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5446f34d91833ce85802e12346709400044b643a --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/tests/checks.json @@ -0,0 +1,129 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "K", + "~J -> K" + ], + "conclusion": "~J" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "~F & J", + "K | J" + ], + "conclusion": "K" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0047/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0047/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0047/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0047/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..c7ff52c0a99aeb38c3999020bee065a9e2155c85 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 15", + "premises": [ + "D -> J", + "J -> F" + ], + "conclusion": "F -> D" + }, + { + "id": "ARG02", + "source": "Sheet 5, question 14", + "premises": [ + "D -> J", + "~D" + ], + "conclusion": "~J" + }, + { + "id": "ARG03", + "source": "Sheet 1, question 3", + "premises": [ + "J", + "~(J & D)" + ], + "conclusion": "~D" + }, + { + "id": "ARG04", + "source": "Sheet 7, question 3", + "premises": [ + "~J & F", + "J <-> ~F" + ], + "conclusion": "F -> J" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 20", + "premises": [ + "~F | ~D", + "F" + ], + "conclusion": "~D" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0056/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/task.toml b/tasks/argument-check/argument-check-validity-d1-t0056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b404f0115a2ac5d9155e2db1556eddd49fea806c --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 56 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0056/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..44e76b5a1256e45660d97ea655c1a7af73b956f3 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "D -> J", + "J -> F" + ], + "conclusion": "F -> D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "D -> J", + "~D" + ], + "conclusion": "~J" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "~J & F", + "J <-> ~F" + ], + "conclusion": "F -> J" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG03", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0056/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0056/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0056/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0056/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..1a7091337dd6e5b7ee151497f268ccbb00bb445d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 3, question 5", + "premises": [ + "P -> ~K", + "K" + ], + "conclusion": "~P" + }, + { + "id": "ARG02", + "source": "Sheet 3, question 4", + "premises": [ + "J & P", + "K -> P" + ], + "conclusion": "~K" + }, + { + "id": "ARG03", + "source": "Sheet 2, question 18", + "premises": [ + "J -> ~K", + "~J & ~K" + ], + "conclusion": "~K" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 16", + "premises": [ + "~P", + "P -> ~K" + ], + "conclusion": "K" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 9", + "premises": [ + "P -> ~K", + "P" + ], + "conclusion": "~K" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0065/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/task.toml b/tasks/argument-check/argument-check-validity-d1-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..896918c2d761b46e46cf712703b0636c213f9dc3 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 65 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0065/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6476a0312c2a42d0706691e9ad10112c8ff1df6b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/tests/checks.json @@ -0,0 +1,129 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "J & P", + "K -> P" + ], + "conclusion": "~K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "~P", + "P -> ~K" + ], + "conclusion": "K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0065/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0065/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0065/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0065/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..21dc6158b5e6442aa871d395f126a42bd3ded3e3 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 3", + "premises": [ + "~(~P & E)", + "~P" + ], + "conclusion": "~E" + }, + { + "id": "ARG02", + "source": "Sheet 8, question 10", + "premises": [ + "E | ~P", + "~E" + ], + "conclusion": "B" + }, + { + "id": "ARG03", + "source": "Sheet 8, question 1", + "premises": [ + "~E -> (B | ~P)", + "~B" + ], + "conclusion": "E" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 9", + "premises": [ + "E | P", + "~E" + ], + "conclusion": "P" + }, + { + "id": "ARG05", + "source": "Sheet 6, question 6", + "premises": [ + "P -> B", + "~B | E" + ], + "conclusion": "E -> P" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0074/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/task.toml b/tasks/argument-check/argument-check-validity-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a2a4bd4a202ae7886f2aad424fb94858b1a2dbb --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 74 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0074/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6b4298215e0c35c8b136bce62321791a120d2561 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "E | ~P", + "~E" + ], + "conclusion": "B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~E -> (B | ~P)", + "~B" + ], + "conclusion": "E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "P -> B", + "~B | E" + ], + "conclusion": "E -> P" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0074/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0074/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0074/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0074/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d1-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..5c40abfdea7f66f20a14d964686885ba8ada6388 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/arguments.json @@ -0,0 +1,47 @@ +[ + { + "id": "ARG01", + "source": "Sheet 9, question 20", + "premises": [ + "H", + "~H | A" + ], + "conclusion": "A" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 14", + "premises": [ + "H -> ~S", + "~H -> ~A" + ], + "conclusion": "~A | ~S" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 8", + "premises": [ + "~H", + "S -> (H | A)" + ], + "conclusion": "~S" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 12", + "premises": [ + "A -> H", + "S -> H" + ], + "conclusion": "A -> S" + }, + { + "id": "ARG05", + "source": "Sheet 7, question 3", + "premises": [ + "S", + "S | A" + ], + "conclusion": "~A" + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/instruction.md b/tasks/argument-check/argument-check-validity-d1-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0cc43d7966322f68ea743b72c5ec754353676ef --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 5 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/solution/oracle.py b/tasks/argument-check/argument-check-validity-d1-t0083/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/solution/solve.sh b/tasks/argument-check/argument-check-validity-d1-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/task.toml b/tasks/argument-check/argument-check-validity-d1-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e34e9190c9888d268a8fbadf471f8273cabcff1 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 83 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/tests/checks.json b/tasks/argument-check/argument-check-validity-d1-t0083/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..7dc9b194b3a1caa1f1c88b9db3af310f83483fc7 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~H", + "S -> (H | A)" + ], + "conclusion": "~S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "A -> H", + "S -> H" + ], + "conclusion": "A -> S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "S", + "S | A" + ], + "conclusion": "~A" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/tests/test.sh b/tasks/argument-check/argument-check-validity-d1-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/tests/validators.py b/tasks/argument-check/argument-check-validity-d1-t0083/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d1-t0083/tests/verify.py b/tasks/argument-check/argument-check-validity-d1-t0083/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d1-t0083/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..2ba4174e8b7ae3bdfdb5f77b45e19295ee800598 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/arguments.json @@ -0,0 +1,76 @@ +[ + { + "id": "ARG01", + "source": "Sheet 3, question 15", + "premises": [ + "F | ~S", + "~S -> R", + "F -> R" + ], + "conclusion": "R" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 14", + "premises": [ + "R -> ~F", + "F | ~A" + ], + "conclusion": "~A -> R" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 5", + "premises": [ + "F & S & S -> (A <-> S)", + "F & S" + ], + "conclusion": "S -> (A <-> S)" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 10", + "premises": [ + "F | A", + "A -> ~F", + "~F & S" + ], + "conclusion": "F <-> S" + }, + { + "id": "ARG05", + "source": "Sheet 5, question 11", + "premises": [ + "R", + "(R & ~S) -> ~F" + ], + "conclusion": "~S -> ~F" + }, + { + "id": "ARG06", + "source": "Sheet 2, question 2", + "premises": [ + "~S", + "S -> ~F & ~A" + ], + "conclusion": "~(~F & ~A)" + }, + { + "id": "ARG07", + "source": "Sheet 8, question 16", + "premises": [ + "S -> F", + "~S -> A" + ], + "conclusion": "A | F" + }, + { + "id": "ARG08", + "source": "Sheet 5, question 14", + "premises": [ + "F | ~A", + "F -> ~R" + ], + "conclusion": "~R" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/instruction.md b/tasks/argument-check/argument-check-validity-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-e0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-e0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/task.toml b/tasks/argument-check/argument-check-validity-d2-e0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e6070714794e467f4a724bf28bc7e93cf94859f8 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10005 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-e0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..03070cccd27f40dfc711f0e69534f2623f2c7750 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "R -> ~F", + "F | ~A" + ], + "conclusion": "~A -> R" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "F | A", + "A -> ~F", + "~F & S" + ], + "conclusion": "F <-> S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "~S", + "S -> ~F & ~A" + ], + "conclusion": "~(~F & ~A)" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "F | ~A", + "F -> ~R" + ], + "conclusion": "~R" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG05", + "ARG07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-e0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-e0005/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-e0005/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-e0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..07d900b8a503c69df59812dde8201513f2066558 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 6, question 14", + "premises": [ + "(K -> ~T) -> ~K | ~D", + "K" + ], + "conclusion": "(K -> ~T) -> ~D" + }, + { + "id": "ARG02", + "source": "Sheet 8, question 7", + "premises": [ + "T", + "~K -> T -> L" + ], + "conclusion": "~K -> L" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 16", + "premises": [ + "~(~L <-> ~K)", + "L & D", + "K <-> ~L | ~D" + ], + "conclusion": "K & ~D" + }, + { + "id": "ARG04", + "source": "Sheet 2, question 9", + "premises": [ + "T & D -> K", + "L -> L & D", + "L | T & D" + ], + "conclusion": "L & D | K" + }, + { + "id": "ARG05", + "source": "Sheet 7, question 10", + "premises": [ + "D -> ~L", + "K -> D" + ], + "conclusion": "~L -> K" + }, + { + "id": "ARG06", + "source": "Sheet 7, question 10", + "premises": [ + "L & (K | ~D)", + "K & L", + "T" + ], + "conclusion": "~D -> K" + }, + { + "id": "ARG07", + "source": "Sheet 9, question 19", + "premises": [ + "~((T | L) & D)", + "~(T | L)" + ], + "conclusion": "D" + }, + { + "id": "ARG08", + "source": "Sheet 1, question 12", + "premises": [ + "D | ~K -> ~D", + "~T -> D | ~K" + ], + "conclusion": "~D -> ~T" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/instruction.md b/tasks/argument-check/argument-check-validity-d2-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-e0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-e0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/task.toml b/tasks/argument-check/argument-check-validity-d2-e0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c5e584bf77ba2acbb6a3f77105e6c7208e64f6c2 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10014 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-e0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cefa75086d27c3137e362f758134ad9847a53eab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~(~L <-> ~K)", + "L & D", + "K <-> ~L | ~D" + ], + "conclusion": "K & ~D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "D -> ~L", + "K -> D" + ], + "conclusion": "~L -> K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~((T | L) & D)", + "~(T | L)" + ], + "conclusion": "D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "D | ~K -> ~D", + "~T -> D | ~K" + ], + "conclusion": "~D -> ~T" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG04", + "ARG06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-e0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-e0014/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-e0014/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-e0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..20099c77c6d873b0a2b6220a88623c00cc756bf5 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 3, question 12", + "premises": [ + "~D -> ~A", + "D -> A & ~Q" + ], + "conclusion": "~A | A & ~Q" + }, + { + "id": "ARG02", + "source": "Sheet 8, question 6", + "premises": [ + "A -> ~D", + "A | ~Q", + "~D & A" + ], + "conclusion": "~D & Q" + }, + { + "id": "ARG03", + "source": "Sheet 1, question 13", + "premises": [ + "(D <-> B) | ~B", + "~B -> ~Q", + "(D <-> B) -> ~Q" + ], + "conclusion": "~Q" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 7", + "premises": [ + "~B | ~Q", + "A -> B" + ], + "conclusion": "~Q -> A" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 18", + "premises": [ + "(Q <-> A) | (B -> ~A)", + "A & B", + "~B & D -> Q & ~D" + ], + "conclusion": "~Q | B" + }, + { + "id": "ARG06", + "source": "Sheet 9, question 4", + "premises": [ + "(Q -> B) -> D | B", + "~D" + ], + "conclusion": "(Q -> B) -> B" + }, + { + "id": "ARG07", + "source": "Sheet 5, question 8", + "premises": [ + "~B | D", + "Q -> B" + ], + "conclusion": "D -> Q" + }, + { + "id": "ARG08", + "source": "Sheet 6, question 7", + "premises": [ + "~B -> Q", + "~B | D" + ], + "conclusion": "Q" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/instruction.md b/tasks/argument-check/argument-check-validity-d2-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-e0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/task.toml b/tasks/argument-check/argument-check-validity-d2-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ee958c2d349ca9f4a293f08964fca93e8a6bf01 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10023 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-e0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..34168fd0a228db5345bc2ecd09c03ae2867097cc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "A -> ~D", + "A | ~Q", + "~D & A" + ], + "conclusion": "~D & Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "~B | ~Q", + "A -> B" + ], + "conclusion": "~Q -> A" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~B | D", + "Q -> B" + ], + "conclusion": "D -> Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "~B -> Q", + "~B | D" + ], + "conclusion": "Q" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG05", + "ARG06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-e0023/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-e0023/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-e0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-e0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..2d61b2d36e2a5c69a42b8bdda870b0e8dd1134bc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 7, question 18", + "premises": [ + "N -> ~S", + "(S -> T) & (~S -> ~T)" + ], + "conclusion": "~T & N" + }, + { + "id": "ARG02", + "source": "Sheet 4, question 14", + "premises": [ + "~P -> (P <-> ~T)", + "T -> S", + "~P | T" + ], + "conclusion": "(P <-> ~T) | S" + }, + { + "id": "ARG03", + "source": "Sheet 9, question 10", + "premises": [ + "(~S <-> ~T) -> P", + "(T -> N) -> ~N | ~S", + "~P | N" + ], + "conclusion": "N -> S" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 6", + "premises": [ + "(S | ~T) -> N", + "P & (N -> T)" + ], + "conclusion": "~N" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 11", + "premises": [ + "~N -> ~S", + "~T & ~N & (T | ~P)" + ], + "conclusion": "~T" + }, + { + "id": "ARG06", + "source": "Sheet 3, question 10", + "premises": [ + "N -> ~P", + "P & T", + "P -> S" + ], + "conclusion": "T -> P" + }, + { + "id": "ARG07", + "source": "Sheet 3, question 20", + "premises": [ + "~N", + "~T -> N | P" + ], + "conclusion": "~T -> P" + }, + { + "id": "ARG08", + "source": "Sheet 6, question 20", + "premises": [ + "~S -> P", + "~S | N" + ], + "conclusion": "P" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/task.toml b/tasks/argument-check/argument-check-validity-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f3f305e6cef4b2c96dbd867c0a8240f20553d17 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 5 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..25886eb9ae8b94cd122b432d91935b420514f293 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "N -> ~S", + "(S -> T) & (~S -> ~T)" + ], + "conclusion": "~T & N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "(~S <-> ~T) -> P", + "(T -> N) -> ~N | ~S", + "~P | N" + ], + "conclusion": "N -> S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "(S | ~T) -> N", + "P & (N -> T)" + ], + "conclusion": "~N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "~S -> P", + "~S | N" + ], + "conclusion": "P" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG05", + "ARG06", + "ARG07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0005/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0005/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..956a67f7073b1ddafecf7399ef50c44628e73943 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/arguments.json @@ -0,0 +1,75 @@ +[ + { + "id": "ARG01", + "source": "Sheet 3, question 11", + "premises": [ + "B -> (~F | D)", + "~(~F | D)" + ], + "conclusion": "~B" + }, + { + "id": "ARG02", + "source": "Sheet 2, question 17", + "premises": [ + "K <-> D -> F", + "F | K" + ], + "conclusion": "~F" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 10", + "premises": [ + "(~F | K) & B", + "F | (K -> ~D)" + ], + "conclusion": "D & B" + }, + { + "id": "ARG04", + "source": "Sheet 5, question 13", + "premises": [ + "~B -> F", + "~B -> K" + ], + "conclusion": "~B -> K & F" + }, + { + "id": "ARG05", + "source": "Sheet 7, question 13", + "premises": [ + "B -> K -> ~F", + "K" + ], + "conclusion": "B -> ~F" + }, + { + "id": "ARG06", + "source": "Sheet 1, question 8", + "premises": [ + "~(B & F)", + "(K -> B) -> (B & F | D)" + ], + "conclusion": "(K -> B) -> D" + }, + { + "id": "ARG07", + "source": "Sheet 8, question 18", + "premises": [ + "B & D -> (F -> ~B)", + "B -> D", + "B <-> ~D" + ], + "conclusion": "F -> B" + }, + { + "id": "ARG08", + "source": "Sheet 4, question 9", + "premises": [ + "~F | ~B -> B", + "~F | ~B -> (K & ~D)" + ], + "conclusion": "B -> K & ~D" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/task.toml b/tasks/argument-check/argument-check-validity-d2-t0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b44472686965b64958de3ec17b1060532f5497f8 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 14 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bff13f024f65267d9797d1fc430b252831647bac --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "K <-> D -> F", + "F | K" + ], + "conclusion": "~F" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "(~F | K) & B", + "F | (K -> ~D)" + ], + "conclusion": "D & B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "B & D -> (F -> ~B)", + "B -> D", + "B <-> ~D" + ], + "conclusion": "F -> B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "~F | ~B -> B", + "~F | ~B -> (K & ~D)" + ], + "conclusion": "B -> K & ~D" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04", + "ARG05", + "ARG06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0014/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0014/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..5e9f26ef4826fcafb224278898f54eb9c58df3d8 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 7, question 1", + "premises": [ + "(B -> K) -> K & D", + "~D -> (K & D)", + "(B -> K) | ~D" + ], + "conclusion": "K & D" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 16", + "premises": [ + "(K -> ~Q) -> K", + "~D -> K" + ], + "conclusion": "~D -> K -> ~Q" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 18", + "premises": [ + "B -> Q", + "Q & D", + "D -> B" + ], + "conclusion": "D & B" + }, + { + "id": "ARG04", + "source": "Sheet 7, question 19", + "premises": [ + "D | K", + "D <-> B <-> ~D" + ], + "conclusion": "B <-> ~D" + }, + { + "id": "ARG05", + "source": "Sheet 4, question 3", + "premises": [ + "~Q <-> K", + "~K" + ], + "conclusion": "D <-> ~B" + }, + { + "id": "ARG06", + "source": "Sheet 9, question 7", + "premises": [ + "D & ~Q -> (~Q <-> ~K)", + "~(~Q <-> ~K)" + ], + "conclusion": "~D" + }, + { + "id": "ARG07", + "source": "Sheet 7, question 11", + "premises": [ + "D -> B | Q", + "D -> ~(B | Q)" + ], + "conclusion": "~D" + }, + { + "id": "ARG08", + "source": "Sheet 7, question 11", + "premises": [ + "B -> (~D & Q)", + "(D <-> Q) | (Q -> D)", + "(D <-> ~B) | D & Q" + ], + "conclusion": "D" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/task.toml b/tasks/argument-check/argument-check-validity-d2-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d87f42c78a0a1e838922f225ef7d071636e804c --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 23 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5734e072933d1971edecbcfb38914a7224a03cec --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/tests/checks.json @@ -0,0 +1,210 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "(K -> ~Q) -> K", + "~D -> K" + ], + "conclusion": "~D -> K -> ~Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "D | K", + "D <-> B <-> ~D" + ], + "conclusion": "B <-> ~D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "~Q <-> K", + "~K" + ], + "conclusion": "D <-> ~B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "D & ~Q -> (~Q <-> ~K)", + "~(~Q <-> ~K)" + ], + "conclusion": "~D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG07", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0023/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0023/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..4ce54af5cf4206b18a39c6545149141224627d75 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/arguments.json @@ -0,0 +1,75 @@ +[ + { + "id": "ARG01", + "source": "Sheet 1, question 16", + "premises": [ + "K | P", + "T & K" + ], + "conclusion": "~T <-> B" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 17", + "premises": [ + "T -> P", + "(~B -> ~P) -> K" + ], + "conclusion": "T | ~P" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 10", + "premises": [ + "B", + "B & P -> T" + ], + "conclusion": "P -> T" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 15", + "premises": [ + "T -> P | ~K", + "~P" + ], + "conclusion": "T -> ~K" + }, + { + "id": "ARG05", + "source": "Sheet 3, question 16", + "premises": [ + "(P <-> K) -> (B & ~T)", + "P -> B & ~T" + ], + "conclusion": "(P <-> K) -> P" + }, + { + "id": "ARG06", + "source": "Sheet 9, question 5", + "premises": [ + "~B -> (T & K | P)", + "~(T & K)" + ], + "conclusion": "~B -> P" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 7", + "premises": [ + "(T -> ~K) -> P", + "~P | K" + ], + "conclusion": "K -> T -> ~K" + }, + { + "id": "ARG08", + "source": "Sheet 3, question 10", + "premises": [ + "B | (P -> T)", + "B -> (P & B)", + "(P -> T) -> P & B" + ], + "conclusion": "P & B" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0032/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/task.toml b/tasks/argument-check/argument-check-validity-d2-t0032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1502e071fe07fc8154f2ab0d031cd365ba553323 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 32 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0032/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d0d1d9e1c0f071e44aac13d0df4f7521a9545174 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/tests/checks.json @@ -0,0 +1,210 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "K | P", + "T & K" + ], + "conclusion": "~T <-> B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "T -> P", + "(~B -> ~P) -> K" + ], + "conclusion": "T | ~P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(P <-> K) -> (B & ~T)", + "P -> B & ~T" + ], + "conclusion": "(P <-> K) -> P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "(T -> ~K) -> P", + "~P | K" + ], + "conclusion": "K -> T -> ~K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG03", + "ARG04", + "ARG06", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0032/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0032/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0032/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0032/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..b58e05d134da2142f9923beb2618f4c36e45d255 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 1, question 7", + "premises": [ + "~Q -> D", + "~Q -> E & Q" + ], + "conclusion": "~Q -> D & (E & Q)" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 9", + "premises": [ + "E | (~A | ~D)", + "E <-> D" + ], + "conclusion": "D" + }, + { + "id": "ARG03", + "source": "Sheet 4, question 15", + "premises": [ + "(Q -> ~E) -> A", + "A -> E" + ], + "conclusion": "E -> Q -> ~E" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 13", + "premises": [ + "(Q -> E) -> ~Q", + "(Q -> E) | E", + "E -> D" + ], + "conclusion": "~Q | D" + }, + { + "id": "ARG05", + "source": "Sheet 5, question 3", + "premises": [ + "E | A", + "A | Q", + "A <-> Q" + ], + "conclusion": "Q | E" + }, + { + "id": "ARG06", + "source": "Sheet 6, question 20", + "premises": [ + "~E", + "E | (Q -> D)" + ], + "conclusion": "Q -> D" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 7", + "premises": [ + "E & ~Q | (~D | E)", + "D | ~E", + "Q | ~A" + ], + "conclusion": "Q" + }, + { + "id": "ARG08", + "source": "Sheet 2, question 7", + "premises": [ + "E & D -> Q", + "~D -> E" + ], + "conclusion": "D -> Q" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0041/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/task.toml b/tasks/argument-check/argument-check-validity-d2-t0041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abc68ddc93595f511804f1bd757e0dca9f519b09 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 41 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0041/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c0364d735e2f456431eb6f56d51cd077e21f02c4 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "E | (~A | ~D)", + "E <-> D" + ], + "conclusion": "D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "(Q -> ~E) -> A", + "A -> E" + ], + "conclusion": "E -> Q -> ~E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "E & ~Q | (~D | E)", + "D | ~E", + "Q | ~A" + ], + "conclusion": "Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "E & D -> Q", + "~D -> E" + ], + "conclusion": "D -> Q" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04", + "ARG05", + "ARG06" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0041/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0041/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0041/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0041/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..fa93f822320056f0f7e9a6fe4338126847607cd2 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/arguments.json @@ -0,0 +1,75 @@ +[ + { + "id": "ARG01", + "source": "Sheet 9, question 18", + "premises": [ + "A -> ~G", + "A -> Q -> T" + ], + "conclusion": "A -> (Q -> T) & ~G" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 17", + "premises": [ + "A -> T", + "~(A -> G)" + ], + "conclusion": "T & A" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 15", + "premises": [ + "~T & Q -> ~T -> G & T", + "~T" + ], + "conclusion": "(~T & Q) -> (G & T)" + }, + { + "id": "ARG04", + "source": "Sheet 1, question 20", + "premises": [ + "~Q | ~G", + "~Q -> (T <-> G)", + "~G -> ~A" + ], + "conclusion": "(T <-> G) | ~A" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 15", + "premises": [ + "(~G -> ~A) -> A", + "(Q -> T) -> A" + ], + "conclusion": "(Q -> T) -> ~G -> ~A" + }, + { + "id": "ARG06", + "source": "Sheet 3, question 18", + "premises": [ + "~(~G | ~T)", + "T & Q -> ~G | ~T" + ], + "conclusion": "~T" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 19", + "premises": [ + "~G", + "Q -> G | T" + ], + "conclusion": "~Q" + }, + { + "id": "ARG08", + "source": "Sheet 4, question 15", + "premises": [ + "T & A", + "Q -> G" + ], + "conclusion": "A & Q" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0050/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/task.toml b/tasks/argument-check/argument-check-validity-d2-t0050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f63ac4a091ef5cb0b6befa71a96c0103fde689ae --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 50 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0050/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ea7354802e5edea71c1b425e44b2d073a1db12ee --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/tests/checks.json @@ -0,0 +1,210 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(~G -> ~A) -> A", + "(Q -> T) -> A" + ], + "conclusion": "(Q -> T) -> ~G -> ~A" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "~(~G | ~T)", + "T & Q -> ~G | ~T" + ], + "conclusion": "~T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~G", + "Q -> G | T" + ], + "conclusion": "~Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "T & A", + "Q -> G" + ], + "conclusion": "A & Q" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG03", + "ARG04" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0050/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0050/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0050/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0050/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..122bc5348fcdc9fc21e78e1fc6a6bf2ef2d64982 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/arguments.json @@ -0,0 +1,77 @@ +[ + { + "id": "ARG01", + "source": "Sheet 2, question 1", + "premises": [ + "D | F", + "F | J <-> F & ~D", + "(F | ~J) | (~J | F)" + ], + "conclusion": "~D <-> F" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 18", + "premises": [ + "D -> F", + "M -> ~F", + "F -> ~J" + ], + "conclusion": "D | F" + }, + { + "id": "ARG03", + "source": "Sheet 6, question 14", + "premises": [ + "(D <-> F) -> D & M", + "M -> D & M", + "M | (D <-> F)" + ], + "conclusion": "D & M" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 17", + "premises": [ + "J -> ~F", + "D -> J" + ], + "conclusion": "D -> ~F" + }, + { + "id": "ARG05", + "source": "Sheet 6, question 7", + "premises": [ + "J", + "(~D <-> J) -> J -> ~F" + ], + "conclusion": "(~D <-> J) -> ~F" + }, + { + "id": "ARG06", + "source": "Sheet 1, question 19", + "premises": [ + "(D <-> ~F) | ~M", + "(D <-> ~F) -> ~J & F" + ], + "conclusion": "~J & F" + }, + { + "id": "ARG07", + "source": "Sheet 1, question 13", + "premises": [ + "~J | ~M", + "~D -> J" + ], + "conclusion": "~M -> ~D" + }, + { + "id": "ARG08", + "source": "Sheet 9, question 9", + "premises": [ + "~F <-> J", + "~F | M" + ], + "conclusion": "J" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0059/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0059/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/task.toml b/tasks/argument-check/argument-check-validity-d2-t0059/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..418ea4e7c32b180de654d1c576c293a2515cf64b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 59 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0059/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a2377343b27625c4153bed139ab63d36a0876799 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "D -> F", + "M -> ~F", + "F -> ~J" + ], + "conclusion": "D | F" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "(D <-> ~F) | ~M", + "(D <-> ~F) -> ~J & F" + ], + "conclusion": "~J & F" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~J | ~M", + "~D -> J" + ], + "conclusion": "~M -> ~D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "~F <-> J", + "~F | M" + ], + "conclusion": "J" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG04", + "ARG05" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0059/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0059/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0059/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0059/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0059/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0068/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..b94d0bf236235300dc1104542da6fec1f074ff32 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/arguments.json @@ -0,0 +1,75 @@ +[ + { + "id": "ARG01", + "source": "Sheet 4, question 8", + "premises": [ + "C <-> K", + "K -> ~C" + ], + "conclusion": "R & C" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 9", + "premises": [ + "~K & (~C <-> R)", + "(C -> R) & (~C | R)", + "(R | C) -> R | ~K" + ], + "conclusion": "K -> ~C" + }, + { + "id": "ARG03", + "source": "Sheet 8, question 7", + "premises": [ + "R <-> K", + "C & (~R & E)" + ], + "conclusion": "K -> ~E" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 11", + "premises": [ + "C -> R & K", + "~C -> E -> K" + ], + "conclusion": "(E -> K) | (R & K)" + }, + { + "id": "ARG05", + "source": "Sheet 1, question 14", + "premises": [ + "(~E -> C) & ~K", + "(K <-> E) -> (R & C)" + ], + "conclusion": "E" + }, + { + "id": "ARG06", + "source": "Sheet 6, question 9", + "premises": [ + "E -> (R | K)", + "~R" + ], + "conclusion": "~E" + }, + { + "id": "ARG07", + "source": "Sheet 5, question 10", + "premises": [ + "~R", + "E -> R | (C <-> R)" + ], + "conclusion": "~E" + }, + { + "id": "ARG08", + "source": "Sheet 4, question 20", + "premises": [ + "E -> C", + "E -> ~R" + ], + "conclusion": "E -> ~R & C" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0068/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0068/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0068/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/task.toml b/tasks/argument-check/argument-check-validity-d2-t0068/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e59de01760361fa31fda307d120d295401c3d8d0 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 68 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0068/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6b76588e9e4cbed6611977f1039ffc0ec196d74d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/tests/checks.json @@ -0,0 +1,210 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "C <-> K", + "K -> ~C" + ], + "conclusion": "R & C" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(~E -> C) & ~K", + "(K <-> E) -> (R & C)" + ], + "conclusion": "E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "E -> (R | K)", + "~R" + ], + "conclusion": "~E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~R", + "E -> R | (C <-> R)" + ], + "conclusion": "~E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG03", + "ARG04", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0068/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0068/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0068/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0068/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0068/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..0b2e00ad421e6141e5ca3198cc1564ace9b5967d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/arguments.json @@ -0,0 +1,76 @@ +[ + { + "id": "ARG01", + "source": "Sheet 2, question 16", + "premises": [ + "~Q", + "B -> Q | R" + ], + "conclusion": "~B" + }, + { + "id": "ARG02", + "source": "Sheet 4, question 6", + "premises": [ + "~E -> Q", + "E -> R" + ], + "conclusion": "R | Q" + }, + { + "id": "ARG03", + "source": "Sheet 4, question 13", + "premises": [ + "Q & E", + "Q & E & (E -> Q)", + "R | E" + ], + "conclusion": "~E & Q" + }, + { + "id": "ARG04", + "source": "Sheet 2, question 6", + "premises": [ + "Q -> (B -> ~E)", + "Q & B" + ], + "conclusion": "~B" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 17", + "premises": [ + "~B", + "(~R & ~Q) -> B" + ], + "conclusion": "R" + }, + { + "id": "ARG06", + "source": "Sheet 5, question 2", + "premises": [ + "B -> E", + "B -> R" + ], + "conclusion": "B -> R & E" + }, + { + "id": "ARG07", + "source": "Sheet 8, question 11", + "premises": [ + "~(E -> Q)", + "B & R", + "~Q | E" + ], + "conclusion": "R & E" + }, + { + "id": "ARG08", + "source": "Sheet 8, question 18", + "premises": [ + "R -> E & R", + "~R -> B" + ], + "conclusion": "E & R | B" + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/instruction.md b/tasks/argument-check/argument-check-validity-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c02498a29bea9adea6fa16be186e8454f2845981 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/instruction.md @@ -0,0 +1,14 @@ +# Argument check: validity + +`arguments.json` holds 8 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/solution/oracle.py b/tasks/argument-check/argument-check-validity-d2-t0077/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/solution/solve.sh b/tasks/argument-check/argument-check-validity-d2-t0077/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/task.toml b/tasks/argument-check/argument-check-validity-d2-t0077/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a3466ae1368e28302d596180477e57cbd33e849 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 77 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/tests/checks.json b/tasks/argument-check/argument-check-validity-d2-t0077/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..50dda706cb9cbb3b9e7d9e3343e92f9fe6904a8a --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/tests/checks.json @@ -0,0 +1,211 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "~Q", + "B -> Q | R" + ], + "conclusion": "~B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "Q & E", + "Q & E & (E -> Q)", + "R | E" + ], + "conclusion": "~E & Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "Q -> (B -> ~E)", + "Q & B" + ], + "conclusion": "~B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "~B", + "(~R & ~Q) -> B" + ], + "conclusion": "R" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG06", + "ARG07", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/tests/test.sh b/tasks/argument-check/argument-check-validity-d2-t0077/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/tests/validators.py b/tasks/argument-check/argument-check-validity-d2-t0077/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d2-t0077/tests/verify.py b/tasks/argument-check/argument-check-validity-d2-t0077/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d2-t0077/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..232f9b18552dac6a17818445661f6cb77564cb47 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/arguments.json @@ -0,0 +1,90 @@ +[ + { + "id": "ARG01", + "source": "Sheet 6, question 12", + "premises": [ + "L -> ~A", + "T -> L", + "(T -> ~L) & (A -> S)" + ], + "conclusion": "~A -> T" + }, + { + "id": "ARG02", + "source": "Sheet 5, question 14", + "premises": [ + "L & (J | T)", + "~S -> ~F -> ~J", + "(~F -> ~J) -> J" + ], + "conclusion": "J -> ~S" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 4", + "premises": [ + "F -> ~A", + "J -> ~A", + "L & J | F" + ], + "conclusion": "J -> F" + }, + { + "id": "ARG04", + "source": "Sheet 3, question 7", + "premises": [ + "~A & (L | F) -> S & A", + "~A" + ], + "conclusion": "L|F->(S&A)" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 7", + "premises": [ + "A & S", + "L", + "L -> (J <-> ~T)" + ], + "conclusion": "J <-> ~T" + }, + { + "id": "ARG06", + "source": "Sheet 7, question 17", + "premises": [ + "(S->F)|(L<->F)", + "S -> F <-> T" + ], + "conclusion": "T" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 12", + "premises": [ + "~F -> T <-> (~J -> ~A)", + "~A", + "S | ~T -> A" + ], + "conclusion": "~(S | ~T)" + }, + { + "id": "ARG08", + "source": "Sheet 9, question 19", + "premises": [ + "~S & ~A <-> (F | T)", + "T -> F <-> S | A", + "A & S" + ], + "conclusion": "~T & S" + }, + { + "id": "ARG09", + "source": "Sheet 3, question 10", + "premises": [ + "L -> ~J", + "T | A", + "~A & T -> L" + ], + "conclusion": "~J->~A&T" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/instruction.md b/tasks/argument-check/argument-check-validity-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-e0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/task.toml b/tasks/argument-check/argument-check-validity-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef9396493f78b20cc9d4d179cd53a3461a5fd72d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10008 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-e0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..26c868d95b18927629ac232d575e13027edbfb65 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/tests/checks.json @@ -0,0 +1,285 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "L -> ~A", + "T -> L", + "(T -> ~L) & (A -> S)" + ], + "conclusion": "~A -> T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "L & (J | T)", + "~S -> ~F -> ~J", + "(~F -> ~J) -> J" + ], + "conclusion": "J -> ~S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "F -> ~A", + "J -> ~A", + "L & J | F" + ], + "conclusion": "J -> F" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "(S->F)|(L<->F)", + "S -> F <-> T" + ], + "conclusion": "T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG09", + "premises": [ + "L -> ~J", + "T | A", + "~A & T -> L" + ], + "conclusion": "~J->~A&T" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG04", + "ARG05", + "ARG07", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-e0008/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-e0008/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-e0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..d8a5df19de5f21d1cf355fd1f01c87a56e949e4b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/arguments.json @@ -0,0 +1,93 @@ +[ + { + "id": "ARG01", + "source": "Sheet 7, question 15", + "premises": [ + "(P<->S)&(~E->~C)", + "~P & ~S", + "E | D" + ], + "conclusion": "P -> A" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 3", + "premises": [ + "A | C & P", + "S <-> ~C", + "A<->E<->P" + ], + "conclusion": "E <-> P" + }, + { + "id": "ARG03", + "source": "Sheet 9, question 20", + "premises": [ + "D | ~E", + "~S | C", + "~(P & S)", + "(~P -> D) | (E <-> ~A)" + ], + "conclusion": "A | D" + }, + { + "id": "ARG04", + "source": "Sheet 6, question 1", + "premises": [ + "C | ~E", + "~E -> ~A & E", + "C->(S->E)" + ], + "conclusion": "(S -> E) | (~A & E)" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 4", + "premises": [ + "A | S -> E", + "(A | S) -> P" + ], + "conclusion": "A | S -> E & P" + }, + { + "id": "ARG06", + "source": "Sheet 7, question 13", + "premises": [ + "(~P -> S) -> (A & C)", + "C <-> ~A", + "~(~A | C)", + "P & ~S -> C" + ], + "conclusion": "S <-> P" + }, + { + "id": "ARG07", + "source": "Sheet 3, question 1", + "premises": [ + "D -> S | P", + "~A -> E", + "~A|D" + ], + "conclusion": "E | (S | P)" + }, + { + "id": "ARG08", + "source": "Sheet 5, question 14", + "premises": [ + "E -> (P <-> A)", + "(C -> A) & (A -> E)", + "E->~P->D" + ], + "conclusion": "(~P -> D) -> (P <-> A)" + }, + { + "id": "ARG09", + "source": "Sheet 5, question 13", + "premises": [ + "A -> C", + "S->C", + "~P|~C" + ], + "conclusion": "A -> S" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/instruction.md b/tasks/argument-check/argument-check-validity-d3-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-e0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-e0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/task.toml b/tasks/argument-check/argument-check-validity-d3-e0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b489c17c214c1f5be862904debd607853c63045 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "eval"] +isced_f = "0223" +family = "validity" +split = "eval" +seed = 10017 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-e0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a9e6653140ab79ecb7df5f5c30ee6e2db06dcfbd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/tests/checks.json @@ -0,0 +1,282 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "A | C & P", + "S <-> ~C", + "A<->E<->P" + ], + "conclusion": "E <-> P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "D | ~E", + "~S | C", + "~(P & S)", + "(~P -> D) | (E <-> ~A)" + ], + "conclusion": "A | D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [ + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "E -> (P <-> A)", + "(C -> A) & (A -> E)", + "E->~P->D" + ], + "conclusion": "(~P -> D) -> (P <-> A)" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG09", + "premises": [ + "A -> C", + "S->C", + "~P|~C" + ], + "conclusion": "A -> S" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04", + "ARG05", + "ARG06", + "ARG07" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-e0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-e0017/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-e0017/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-e0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-e0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..6a617582f1ac2e4f69f2aab515ac53104f7e0014 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/arguments.json @@ -0,0 +1,94 @@ +[ + { + "id": "ARG01", + "source": "Sheet 5, question 10", + "premises": [ + "N -> T", + "~N->L&~G", + "~T" + ], + "conclusion": "~N" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 9", + "premises": [ + "G & T", + "~Q", + "Q <-> (N | ~S)" + ], + "conclusion": "~G" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 16", + "premises": [ + "~L", + "Q & ~S", + "S <-> N", + "Q & L" + ], + "conclusion": "S" + }, + { + "id": "ARG04", + "source": "Sheet 3, question 20", + "premises": [ + "~(L&~N)", + "N<->~T", + "(N <-> ~T) -> (T <-> Q)" + ], + "conclusion": "T<->Q" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 13", + "premises": [ + "(S <-> ~T) & (Q -> ~G)", + "(S & ~Q) -> L -> ~N", + "~(Q <-> T)", + "G -> S" + ], + "conclusion": "N & L" + }, + { + "id": "ARG06", + "source": "Sheet 1, question 14", + "premises": [ + "G|Q", + "~((G | Q) & L)", + "G -> N" + ], + "conclusion": "~L" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 4", + "premises": [ + "~S -> T", + "(N & S) -> T -> ~N", + "~T | ~L" + ], + "conclusion": "~L->~S" + }, + { + "id": "ARG08", + "source": "Sheet 6, question 9", + "premises": [ + "N -> (~L -> S)", + "T -> ~L -> S", + "Q -> ~G" + ], + "conclusion": "T -> N" + }, + { + "id": "ARG09", + "source": "Sheet 9, question 3", + "premises": [ + "L -> Q", + "L -> T", + "N | L -> (~S | L)" + ], + "conclusion": "L -> T & Q" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/task.toml b/tasks/argument-check/argument-check-validity-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0fa514a79b436d7f2622534d11a6aa0c4032b45a --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 8 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4057232350057ef7bbc86f7405e9248ac5ad9b8d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/tests/checks.json @@ -0,0 +1,284 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "G & T", + "~Q", + "Q <-> (N | ~S)" + ], + "conclusion": "~G" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.essential_premises", + "type": "set", + "value": [ + 1, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(S <-> ~T) & (Q -> ~G)", + "(S & ~Q) -> L -> ~N", + "~(Q <-> T)", + "G -> S" + ], + "conclusion": "N & L" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "~S -> T", + "(N & S) -> T -> ~N", + "~T | ~L" + ], + "conclusion": "~L->~S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "N -> (~L -> S)", + "T -> ~L -> S", + "Q -> ~G" + ], + "conclusion": "T -> N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG04", + "ARG06", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0008/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0008/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..f08a23722a5e4e6f13f4b32b42671d3caa57223b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/arguments.json @@ -0,0 +1,94 @@ +[ + { + "id": "ARG01", + "source": "Sheet 9, question 3", + "premises": [ + "K | ~M -> K & A", + "T | K", + "A | ~T -> K" + ], + "conclusion": "~T | M" + }, + { + "id": "ARG02", + "source": "Sheet 6, question 5", + "premises": [ + "(~T -> A) -> (~C & A)", + "T & ~A", + "~N & (C | T)", + "~T & C" + ], + "conclusion": "N | A" + }, + { + "id": "ARG03", + "source": "Sheet 6, question 2", + "premises": [ + "(N -> ~A) -> (A <-> T)", + "(N -> ~A) -> C" + ], + "conclusion": "C -> (A <-> T)" + }, + { + "id": "ARG04", + "source": "Sheet 4, question 11", + "premises": [ + "M & ~K", + "~T -> (~M <-> A)", + "~T | A" + ], + "conclusion": "~M <-> A" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 19", + "premises": [ + "A & K", + "~N & M", + "A", + "N->M->C" + ], + "conclusion": "A & N" + }, + { + "id": "ARG06", + "source": "Sheet 1, question 6", + "premises": [ + "~T", + "A <-> ~C", + "T | (M <-> A)" + ], + "conclusion": "M<->A" + }, + { + "id": "ARG07", + "source": "Sheet 4, question 4", + "premises": [ + "T -> ~A <-> ~T", + "(T -> ~A) | C", + "A|K" + ], + "conclusion": "~T" + }, + { + "id": "ARG08", + "source": "Sheet 4, question 11", + "premises": [ + "M -> K | ~C", + "~K & N", + "(M <-> K) | ~T & N", + "(~N -> A) & (C & ~A)" + ], + "conclusion": "~M" + }, + { + "id": "ARG09", + "source": "Sheet 2, question 9", + "premises": [ + "T -> ~K", + "~C -> ~A", + "~C | T" + ], + "conclusion": "~A | ~K" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/task.toml b/tasks/argument-check/argument-check-validity-d3-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..98c2d194c13106636693254d0769cee4f490b085 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 17 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..981aba53cc7a54690fb5018211936ba5e4e6d99f --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/tests/checks.json @@ -0,0 +1,287 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "K | ~M -> K & A", + "T | K", + "A | ~T -> K" + ], + "conclusion": "~T | M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.essential_premises", + "type": "set", + "value": [ + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "(N -> ~A) -> (A <-> T)", + "(N -> ~A) -> C" + ], + "conclusion": "C -> (A <-> T)" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "M & ~K", + "~T -> (~M <-> A)", + "~T | A" + ], + "conclusion": "~M <-> A" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "A & K", + "~N & M", + "A", + "N->M->C" + ], + "conclusion": "A & N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "T -> ~A <-> ~T", + "(T -> ~A) | C", + "A|K" + ], + "conclusion": "~T" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG06", + "ARG08", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0017/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0017/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..c210a347806287484b50f32e8b2587272853758b --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/arguments.json @@ -0,0 +1,93 @@ +[ + { + "id": "ARG01", + "source": "Sheet 2, question 2", + "premises": [ + "~R", + "~R & T -> R | A & H" + ], + "conclusion": "~R & T -> A & H" + }, + { + "id": "ARG02", + "source": "Sheet 9, question 16", + "premises": [ + "T <-> K", + "(K -> ~R) | C", + "K -> ~R <-> ~K" + ], + "conclusion": "~K" + }, + { + "id": "ARG03", + "source": "Sheet 5, question 3", + "premises": [ + "C -> ~A", + "H<->A", + "A & C & (R | H)" + ], + "conclusion": "A -> ~R" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 17", + "premises": [ + "(C | H) | H & K", + "(C -> R) | (~A <-> R)", + "~A & ~T", + "~A & C" + ], + "conclusion": "K -> ~C" + }, + { + "id": "ARG05", + "source": "Sheet 4, question 4", + "premises": [ + "H -> K", + "H -> ~T", + "(K | ~T) & (~K | ~A)" + ], + "conclusion": "~T -> K" + }, + { + "id": "ARG06", + "source": "Sheet 5, question 5", + "premises": [ + "~C->K&T", + "C & T & (C <-> T)", + "K | R" + ], + "conclusion": "C | K" + }, + { + "id": "ARG07", + "source": "Sheet 1, question 11", + "premises": [ + "~T <-> ~C", + "K->(K<->T)", + "K->T->H" + ], + "conclusion": "K -> (K <-> T) & (T -> H)" + }, + { + "id": "ARG08", + "source": "Sheet 2, question 4", + "premises": [ + "K | (~T | C)", + "K&A", + "~T | C -> C", + "K -> C" + ], + "conclusion": "C" + }, + { + "id": "ARG09", + "source": "Sheet 4, question 3", + "premises": [ + "~T", + "(A <-> ~C) <-> ~K", + "(A <-> ~C) | ~R" + ], + "conclusion": "~K" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0026/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/task.toml b/tasks/argument-check/argument-check-validity-d3-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0d083855c90274e4fe71871b9d84c73790c735c7 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 26 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0026/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..fc4ef6aa0e893b83aedc91989d68944256665c37 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/tests/checks.json @@ -0,0 +1,279 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "T <-> K", + "(K -> ~R) | C", + "K -> ~R <-> ~K" + ], + "conclusion": "~K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "(C | H) | H & K", + "(C -> R) | (~A <-> R)", + "~A & ~T", + "~A & C" + ], + "conclusion": "K -> ~C" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "H -> K", + "H -> ~T", + "(K | ~T) & (~K | ~A)" + ], + "conclusion": "~T -> K" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG09", + "premises": [ + "~T", + "(A <-> ~C) <-> ~K", + "(A <-> ~C) | ~R" + ], + "conclusion": "~K" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG03", + "ARG06", + "ARG07", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0026/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0026/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0026/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0026/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..faa26e27297fd87b57096e935e9fe24b0cd38847 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/arguments.json @@ -0,0 +1,94 @@ +[ + { + "id": "ARG01", + "source": "Sheet 7, question 8", + "premises": [ + "B <-> ~D", + "C <-> F", + "G&F" + ], + "conclusion": "~B|N" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 19", + "premises": [ + "~C|~B", + "C -> D", + "D & B", + "(~B&~D)|(N|C)" + ], + "conclusion": "G & C" + }, + { + "id": "ARG03", + "source": "Sheet 3, question 12", + "premises": [ + "~B & N", + "~D -> B -> F", + "(D -> B) -> N -> D", + "~(B | N)" + ], + "conclusion": "D & ~B" + }, + { + "id": "ARG04", + "source": "Sheet 9, question 8", + "premises": [ + "D -> F", + "~B -> (D -> F) -> G -> F" + ], + "conclusion": "~B -> G -> F" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 20", + "premises": [ + "N & D -> C | G", + "~C | G", + "N" + ], + "conclusion": "D -> C | G" + }, + { + "id": "ARG06", + "source": "Sheet 9, question 5", + "premises": [ + "(N & B) -> D", + "B | N", + "D | ~B <-> ~D | B", + "(D & G) <-> ~G <-> ~N" + ], + "conclusion": "D & G" + }, + { + "id": "ARG07", + "source": "Sheet 6, question 15", + "premises": [ + "G->F", + "N -> ~D", + "N -> C" + ], + "conclusion": "~D -> C" + }, + { + "id": "ARG08", + "source": "Sheet 9, question 12", + "premises": [ + "~N", + "N | D", + "(~N <-> ~C) & (D | ~G)" + ], + "conclusion": "D" + }, + { + "id": "ARG09", + "source": "Sheet 5, question 20", + "premises": [ + "~B<->D->N", + "~(~G & F)", + "G" + ], + "conclusion": "F" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0035/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/task.toml b/tasks/argument-check/argument-check-validity-d3-t0035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..903a61efc96d26d3941c761dc589d8d19b9f52bd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 35 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0035/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3df7e2b0faeb0675fdde86ca5ef59fc718e08c6d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/tests/checks.json @@ -0,0 +1,287 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "B <-> ~D", + "C <-> F", + "G&F" + ], + "conclusion": "~B|N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "~C|~B", + "C -> D", + "D & B", + "(~B&~D)|(N|C)" + ], + "conclusion": "G & C" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "(N & B) -> D", + "B | N", + "D | ~B <-> ~D | B", + "(D & G) <-> ~G <-> ~N" + ], + "conclusion": "D & G" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "G->F", + "N -> ~D", + "N -> C" + ], + "conclusion": "~D -> C" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG09", + "premises": [ + "~B<->D->N", + "~(~G & F)", + "G" + ], + "conclusion": "F" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG03", + "ARG04", + "ARG05", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0035/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0035/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0035/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0035/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..8c9704d6df22b1416e9a9f8da49422e58871e14d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/arguments.json @@ -0,0 +1,93 @@ +[ + { + "id": "ARG01", + "source": "Sheet 2, question 14", + "premises": [ + "Q -> D", + "H -> N", + "Q | H" + ], + "conclusion": "D | N" + }, + { + "id": "ARG02", + "source": "Sheet 9, question 3", + "premises": [ + "Q <-> D", + "Q & H", + "D -> ~H", + "~Q & (~D <-> N)" + ], + "conclusion": "~H->D" + }, + { + "id": "ARG03", + "source": "Sheet 4, question 20", + "premises": [ + "~(N | H)", + "H <-> M", + "M <-> Q" + ], + "conclusion": "~H" + }, + { + "id": "ARG04", + "source": "Sheet 3, question 10", + "premises": [ + "~(~D <-> H)", + "H->Q", + "M -> Q" + ], + "conclusion": "H -> M" + }, + { + "id": "ARG05", + "source": "Sheet 9, question 12", + "premises": [ + "(H<->M)->D->H", + "~D | M | (Q & E)", + "~D | M -> (M <-> H)" + ], + "conclusion": "M <-> H" + }, + { + "id": "ARG06", + "source": "Sheet 7, question 4", + "premises": [ + "N&H->D", + "D | H | N & M", + "M | ~H <-> ~D & N" + ], + "conclusion": "~M | ~D" + }, + { + "id": "ARG07", + "source": "Sheet 1, question 19", + "premises": [ + "(E -> ~M) -> H -> Q", + "~E", + "H & ~N" + ], + "conclusion": "Q -> N" + }, + { + "id": "ARG08", + "source": "Sheet 1, question 9", + "premises": [ + "~Q -> ~N", + "~H | ~Q", + "~H -> D" + ], + "conclusion": "D | ~N" + }, + { + "id": "ARG09", + "source": "Sheet 7, question 15", + "premises": [ + "Q | (D -> N)", + "H | E -> ~D", + "H | E | M" + ], + "conclusion": "~D" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0044/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/task.toml b/tasks/argument-check/argument-check-validity-d3-t0044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f14e612d5c83f4ad0588344336f527a6a756791 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 44 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0044/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cccff81eea32c753e3491a7735e2cd6e9bc21629 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/tests/checks.json @@ -0,0 +1,282 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.essential_premises", + "type": "set", + "value": [ + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "~(~D <-> H)", + "H->Q", + "M -> Q" + ], + "conclusion": "H -> M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(H<->M)->D->H", + "~D | M | (Q & E)", + "~D | M -> (M <-> H)" + ], + "conclusion": "M <-> H" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "(E -> ~M) -> H -> Q", + "~E", + "H & ~N" + ], + "conclusion": "Q -> N" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG09", + "premises": [ + "Q | (D -> N)", + "H | E -> ~D", + "H | E | M" + ], + "conclusion": "~D" + }, + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG03", + "ARG06", + "ARG08" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0044/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0044/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0044/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0044/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..a3db2aea853da26b68a5a52868a0e1acbe8cdfdc --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/arguments.json @@ -0,0 +1,94 @@ +[ + { + "id": "ARG01", + "source": "Sheet 4, question 17", + "premises": [ + "~B", + "~T & D <-> ~D <-> ~F", + "M -> (~B -> G)" + ], + "conclusion": "M -> G" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 11", + "premises": [ + "(~T -> M) & (F -> M)", + "~G -> D -> F", + "D" + ], + "conclusion": "~G -> F" + }, + { + "id": "ARG03", + "source": "Sheet 5, question 17", + "premises": [ + "(~M | T) & (~M & ~G)", + "D&G", + "B | ~M" + ], + "conclusion": "~M" + }, + { + "id": "ARG04", + "source": "Sheet 7, question 12", + "premises": [ + "~F & B", + "(F -> G) -> D", + "B -> D", + "B|(F->G)" + ], + "conclusion": "D" + }, + { + "id": "ARG05", + "source": "Sheet 7, question 15", + "premises": [ + "D & ~G", + "F->M->~D", + "M & T -> M -> ~D" + ], + "conclusion": "F -> (M & T)" + }, + { + "id": "ARG06", + "source": "Sheet 6, question 9", + "premises": [ + "~T & G -> ~B -> ~F", + "T & F", + "(~G->T)&F", + "~B" + ], + "conclusion": "T & B" + }, + { + "id": "ARG07", + "source": "Sheet 2, question 17", + "premises": [ + "G|~B|M", + "(~G -> M) | (D | ~F)", + "(~B | D) & (~D & M)" + ], + "conclusion": "F|G" + }, + { + "id": "ARG08", + "source": "Sheet 1, question 8", + "premises": [ + "(B -> D) -> (D <-> M)", + "B -> ~D", + "~(G <-> F)", + "~B" + ], + "conclusion": "F -> D" + }, + { + "id": "ARG09", + "source": "Sheet 2, question 6", + "premises": [ + "B & ~M -> ~T | G", + "B" + ], + "conclusion": "~M -> (~T | G)" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0053/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/task.toml b/tasks/argument-check/argument-check-validity-d3-t0053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..baca9b99471c597ece2b2f8798077bb4e42a0cdd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 53 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0053/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..96d00059dfe758412e6639ce30080ba96adb6a33 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/tests/checks.json @@ -0,0 +1,281 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "D & ~G", + "F->M->~D", + "M & T -> M -> ~D" + ], + "conclusion": "F -> (M & T)" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "~T & G -> ~B -> ~F", + "T & F", + "(~G->T)&F", + "~B" + ], + "conclusion": "T & B" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "G|~B|M", + "(~G -> M) | (D | ~F)", + "(~B | D) & (~D & M)" + ], + "conclusion": "F|G" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "(B -> D) -> (D <-> M)", + "B -> ~D", + "~(G <-> F)", + "~B" + ], + "conclusion": "F -> D" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG02", + "ARG03", + "ARG04", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0053/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0053/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0053/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0053/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..051b8544942d2172ac28ff777d4b9c35014ddd6d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/arguments.json @@ -0,0 +1,96 @@ +[ + { + "id": "ARG01", + "source": "Sheet 8, question 8", + "premises": [ + "~(L | E)", + "~T -> L | E | ~M" + ], + "conclusion": "~T -> ~M" + }, + { + "id": "ARG02", + "source": "Sheet 7, question 11", + "premises": [ + "E->~T", + "T | ~L -> Q & T", + "(L <-> T) | (T <-> B)", + "L & B" + ], + "conclusion": "B<->M" + }, + { + "id": "ARG03", + "source": "Sheet 7, question 10", + "premises": [ + "B & ~M", + "~T|~B", + "(T | B) -> ~T | ~B", + "~B|Q" + ], + "conclusion": "Q&M" + }, + { + "id": "ARG04", + "source": "Sheet 4, question 20", + "premises": [ + "~(M|E)", + "L", + "T|~M", + "~L | ~B | M & L" + ], + "conclusion": "~M&~E" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 20", + "premises": [ + "(L -> Q) -> L", + "Q<->M|~L", + "~L | B" + ], + "conclusion": "B->L->Q" + }, + { + "id": "ARG06", + "source": "Sheet 6, question 1", + "premises": [ + "~E -> B", + "B", + "(~E | T) & (T & Q)" + ], + "conclusion": "~E" + }, + { + "id": "ARG07", + "source": "Sheet 1, question 17", + "premises": [ + "~T & E", + "~T & B", + "B & E", + "(~T & B) & (~M & L)" + ], + "conclusion": "M <-> ~E" + }, + { + "id": "ARG08", + "source": "Sheet 8, question 12", + "premises": [ + "(B <-> ~L) & (E <-> M)", + "L | ~T -> ~M | E", + "T&L", + "B | ~Q" + ], + "conclusion": "~Q & ~L" + }, + { + "id": "ARG09", + "source": "Sheet 9, question 1", + "premises": [ + "~L | ~E & ~T", + "~L->Q", + "~E & ~T -> T" + ], + "conclusion": "Q | T" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0062/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/task.toml b/tasks/argument-check/argument-check-validity-d3-t0062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..339847ea6cef7d25f72ce67f7c8f8d0e28299501 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 62 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0062/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bca226d1b512c383b8acaa5ef5e78ef0623e43f9 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/tests/checks.json @@ -0,0 +1,288 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG02", + "premises": [ + "E->~T", + "T | ~L -> Q & T", + "(L <-> T) | (T <-> B)", + "L & B" + ], + "conclusion": "B<->M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "B & ~M", + "~T|~B", + "(T | B) -> ~T | ~B", + "~B|Q" + ], + "conclusion": "Q&M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG05", + "premises": [ + "(L -> Q) -> L", + "Q<->M|~L", + "~L | B" + ], + "conclusion": "B->L->Q" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG06", + "premises": [ + "~E -> B", + "B", + "(~E | T) & (T & Q)" + ], + "conclusion": "~E" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.essential_premises", + "type": "set", + "value": [ + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "(B <-> ~L) & (E <-> M)", + "L | ~T -> ~M | E", + "T&L", + "B | ~Q" + ], + "conclusion": "~Q & ~L" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 1, + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG01", + "ARG04", + "ARG07", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0062/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0062/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0062/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0062/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..cb9b3579956a3768f0fce279fa2680a97f577034 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/arguments.json @@ -0,0 +1,93 @@ +[ + { + "id": "ARG01", + "source": "Sheet 1, question 16", + "premises": [ + "~S|~R", + "~S|K<->R", + "~S <-> P" + ], + "conclusion": "P" + }, + { + "id": "ARG02", + "source": "Sheet 1, question 8", + "premises": [ + "~H", + "~(~H & ~K)", + "(~S | K) | (H -> C)" + ], + "conclusion": "K" + }, + { + "id": "ARG03", + "source": "Sheet 8, question 8", + "premises": [ + "~R & ~C & (C | ~S)", + "H -> ~S | C", + "S -> ~S | C" + ], + "conclusion": "H -> S" + }, + { + "id": "ARG04", + "source": "Sheet 2, question 17", + "premises": [ + "P", + "H -> K", + "~K|C" + ], + "conclusion": "C -> H" + }, + { + "id": "ARG05", + "source": "Sheet 5, question 17", + "premises": [ + "H -> (S | R)", + "H -> R <-> ~S", + "H & C", + "S<->R" + ], + "conclusion": "R | ~H" + }, + { + "id": "ARG06", + "source": "Sheet 7, question 15", + "premises": [ + "(H <-> R) -> K | P", + "~K" + ], + "conclusion": "(H <-> R) -> P" + }, + { + "id": "ARG07", + "source": "Sheet 6, question 1", + "premises": [ + "~P -> ~H", + "~R&S", + "~P -> ~K" + ], + "conclusion": "~P -> ~K & ~H" + }, + { + "id": "ARG08", + "source": "Sheet 1, question 2", + "premises": [ + "~(~C | P)", + "S -> C", + "~R -> C" + ], + "conclusion": "~R -> S" + }, + { + "id": "ARG09", + "source": "Sheet 8, question 15", + "premises": [ + "C & R", + "(R & K) | ~K", + "R & K -> ~S & R", + "~K -> (~S & R)" + ], + "conclusion": "~S&R" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0071/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/task.toml b/tasks/argument-check/argument-check-validity-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5bb6efe1e0e329eca7e5e8a33851642119fb542a --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 71 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0071/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..aa92806e65694510f915375d5c621302bf56d6eb --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/tests/checks.json @@ -0,0 +1,282 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "~S|~R", + "~S|K<->R", + "~S <-> P" + ], + "conclusion": "P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~R & ~C & (C | ~S)", + "H -> ~S | C", + "S -> ~S | C" + ], + "conclusion": "H -> S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "P", + "H -> K", + "~K|C" + ], + "conclusion": "C -> H" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.essential_premises", + "type": "set", + "value": [ + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.essential_premises", + "type": "set", + "value": [ + 1, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG08", + "premises": [ + "~(~C | P)", + "S -> C", + "~R -> C" + ], + "conclusion": "~R -> S" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 3, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG05", + "ARG06", + "ARG07", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0071/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0071/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0071/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0071/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/environment/Dockerfile b/tasks/argument-check/argument-check-validity-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/arguments.json b/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/arguments.json new file mode 100644 index 0000000000000000000000000000000000000000..68b065b71b41e047ff5d709abbd892f0956dba5d --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/arguments.json @@ -0,0 +1,95 @@ +[ + { + "id": "ARG01", + "source": "Sheet 6, question 16", + "premises": [ + "E|(L->M)", + "P | G", + "(~L | ~P) -> M" + ], + "conclusion": "M -> P" + }, + { + "id": "ARG02", + "source": "Sheet 8, question 3", + "premises": [ + "~M & E", + "(L->E)&H", + "M <-> G", + "~G | (L <-> E)" + ], + "conclusion": "E" + }, + { + "id": "ARG03", + "source": "Sheet 1, question 11", + "premises": [ + "~(G & M)", + "~G & M", + "E -> M" + ], + "conclusion": "~E <-> H" + }, + { + "id": "ARG04", + "source": "Sheet 7, question 12", + "premises": [ + "(L&E)|(~H<->G)", + "E|~G", + "~L & E -> M -> P", + "~M" + ], + "conclusion": "L | M" + }, + { + "id": "ARG05", + "source": "Sheet 8, question 1", + "premises": [ + "P | G <-> G | M", + "~(P & G)", + "P & G <-> G -> ~E" + ], + "conclusion": "~(G -> ~E)" + }, + { + "id": "ARG06", + "source": "Sheet 9, question 1", + "premises": [ + "H -> G", + "M | ~P <-> H", + "~H -> P" + ], + "conclusion": "G | P" + }, + { + "id": "ARG07", + "source": "Sheet 2, question 13", + "premises": [ + "H -> ~G", + "~H", + "(~G <-> H) <-> ~M & L" + ], + "conclusion": "G" + }, + { + "id": "ARG08", + "source": "Sheet 2, question 9", + "premises": [ + "H->G", + "H -> ~G", + "M & ~E" + ], + "conclusion": "~H" + }, + { + "id": "ARG09", + "source": "Sheet 1, question 6", + "premises": [ + "(~G -> ~H) -> M & P", + "M&H", + "P -> G", + "G&~H" + ], + "conclusion": "~G & ~M" + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/logic_reference.md b/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/logic_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04702181b4aa6dac28b6db16669105a115c5a6 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/environment/workdir/logic_reference.md @@ -0,0 +1,48 @@ +# Logic reference + +## Formulas + +- An atom is a single capital letter, `A` to `Z`. +- `~X` means not X. +- `X & Y` means X and Y. +- `X | Y` means X or Y (inclusive: one or the other or both). +- `X -> Y` means if X then Y. +- `X <-> Y` means X if and only if Y. +- Parentheses `(` and `)` group. Spaces between symbols are optional and carry no meaning. + +## Reading a formula that is not fully parenthesised + +The connectives bind in this order, from tightest to loosest: `~`, then `&`, then `|`, then `->`, then `<->`. + +- `~` applies to the shortest formula that follows it: an atom, a parenthesised formula or another negation. So `~A & B` is `(~A) & B`. +- `A & B | C` is `(A & B) | C`, and `A | B & C` is `A | (B & C)`. +- `A | B -> C & D` is `(A | B) -> (C & D)`. +- `A -> B <-> C` is `(A -> B) <-> C`. +- `&` and `|` group to the left: `A & B & C` is `(A & B) & C`. +- `->` and `<->` group to the right: `A -> B -> C` is `A -> (B -> C)`, and `A <-> B <-> C` is `A <-> (B <-> C)`. + +## Truth conditions + +| X | Y | ~X | X & Y | X \| Y | X -> Y | X <-> Y | +|---|---|---|---|---|---|---| +| true | true | false | true | true | true | true | +| true | false | false | false | true | false | false | +| false | true | true | false | true | true | false | +| false | false | true | false | false | true | true | + +## Valuations and rows + +A valuation gives each atom the value true or false. For one problem (one argument, one set of sentences or one pair of formulas) the atoms that occur are the atoms that appear in at least one of its formulas. The truth table of the problem has one row for each valuation of the atoms that occur: 2 to the power n rows for n atoms. Every count of rows or valuations asked for is a count over this table. + +In `answer.json` a valuation is a JSON object whose keys are exactly the atoms that occur in the problem and whose values are the JSON booleans `true` and `false`, for example `{"A": true, "B": false}`. Leave no atom out and add none. + +## Definitions + +- An argument is **valid** if there is no row in which every premise is true and the conclusion is false. Otherwise it is invalid, and any such row is a **counterexample**. An argument whose premises are never all true together is therefore valid. +- A premise of a valid argument is **essential** if the argument becomes invalid when that one premise is deleted and the others are kept. +- A set of sentences is **satisfiable** (consistent) if at least one row makes every sentence in it true. Such a row is a **model** of the set. +- An atom is **forced true** by a satisfiable set if it is true in every model of the set, and **forced false** if it is false in every model. +- Two formulas are **equivalent** if they have the same truth value in every row. A row in which they differ is a **distinguishing valuation**. +- A **literal** is an atom or `~` followed by an atom (`~~A` is not a literal). +- A formula is in **conjunctive normal form (CNF)** if, once parsed by the rules above, it is a conjunction (`&`) of one or more clauses, where each clause is a disjunction (`|`) of one or more literals. `(A | ~B) & C` and `A | B` and `~A` are in CNF. `A | B & C` is not: it parses as `A | (B & C)`. `->` and `<->` do not occur in a CNF. +- A formula is in **disjunctive normal form (DNF)** if, once parsed, it is a disjunction (`|`) of one or more terms, where each term is a conjunction (`&`) of one or more literals. `A & ~B | C` and `A & B` are in DNF. diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/instruction.md b/tasks/argument-check/argument-check-validity-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51ed52e4d4297838ce058392325f0020c0653294 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/instruction.md @@ -0,0 +1,15 @@ +# Argument check: validity + +`arguments.json` holds 9 arguments in propositional logic, each with its premises and a conclusion. `logic_reference.md` gives the formula syntax, including how to read formulas that are not fully parenthesised, and the definitions to apply. + +Test every argument with a full truth table over the atoms that occur in it. + +Write `answer.json` in this folder, a JSON object with: + +- `arguments`: an object keyed by argument id. For each argument give + - `valid`: `true` or `false`. + - `premise_true_rows`: the number of rows in which every premise is true, as an integer. + - `counterexample_rows`: the number of rows in which every premise is true and the conclusion is false, as an integer (0 for a valid argument). + - `counterexample`: for an invalid argument, one counterexample written as a valuation (an object giving `true` or `false` to exactly the atoms that occur in the argument). Any counterexample is accepted. For a valid argument give `null`. + - `essential_premises`: for a valid argument only, the list of premise numbers (1 for the first premise in the file, 2 for the second, and so on) that are essential as defined in the reference. Any order; an empty list if none. +- `valid_ids`: list of the ids of the valid arguments (any order). diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/solution/oracle.py b/tasks/argument-check/argument-check-validity-d3-t0080/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a559afcecc03a6e202b78b7d3818db23719046 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/solution/oracle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Reference solution for Argument Check. Works only from the files in the current directory. + +Formulas are read with a shunting-yard pass into reverse Polish notation and evaluated on a stack, +following the precedence and grouping rules of logic_reference.md. +""" +import json, os + +BINDING = {"~": 5, "&": 4, "|": 3, "->": 2, "<->": 1} +GROUPS_RIGHT = {"~", "->", "<->"} + +def lex(text): + toks, i = [], 0 + while i < len(text): + c = text[i] + if c.isspace(): i += 1; continue + if text[i:i + 3] == "<->": toks.append("<->"); i += 3; continue + if text[i:i + 2] == "->": toks.append("->"); i += 2; continue + if c in "~&|()" or (len(c) == 1 and "A" <= c <= "Z"): toks.append(c); i += 1; continue + raise ValueError("cannot read %r" % text) + return toks + +def to_rpn(text): + out, ops = [], [] + expect_operand = True + for t in lex(text): + if t not in BINDING and t not in "()": # an atom + if not expect_operand: raise ValueError(text) + out.append(t); expect_operand = False + elif t == "~": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == "(": + if not expect_operand: raise ValueError(text) + ops.append(t) + elif t == ")": + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(": out.append(ops.pop()) + if not ops: raise ValueError(text) + ops.pop() + else: # a two-place connective + if expect_operand: raise ValueError(text) + while ops and ops[-1] != "(" and (BINDING[ops[-1]] > BINDING[t] or (BINDING[ops[-1]] == BINDING[t] and t not in GROUPS_RIGHT)): + out.append(ops.pop()) + ops.append(t); expect_operand = True + if expect_operand: raise ValueError(text) + while ops: + if ops[-1] == "(": raise ValueError(text) + out.append(ops.pop()) + return out + +def run(rpn, val): + st = [] + for t in rpn: + if t == "~": st.append(not st.pop()) + elif t in BINDING: + y = st.pop(); x = st.pop() + st.append((x and y) if t == "&" else (x or y) if t == "|" else ((not x) or y) if t == "->" else (x == y)) + else: st.append(val[t]) + assert len(st) == 1 + return st[0] + +def letters(rpns): + return sorted(set(t for rpn in rpns for t in rpn if t not in BINDING)) + +def all_rows(atoms): + rows = [] + for k in range(2 ** len(atoms)): + rows.append(dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))) + return rows + +def load(name): + with open(name) as f: return json.load(f) + +def validity(): + ans = {"arguments": {}, "valid_ids": []} + for arg in load("arguments.json"): + prem = [to_rpn(p) for p in arg["premises"]]; concl = to_rpn(arg["conclusion"]) + rows = all_rows(letters(prem + [concl])) + def bad_rows(ps): + return [v for v in rows if all(run(p, v) for p in ps) and not run(concl, v)] + p_true = sum(1 for v in rows if all(run(p, v) for p in prem)) + cex = bad_rows(prem) + rec = {"valid": not cex, "premise_true_rows": p_true, "counterexample_rows": len(cex), "counterexample": cex[0] if cex else None} + if not cex: + rec["essential_premises"] = [i + 1 for i in range(len(prem)) if bad_rows(prem[:i] + prem[i + 1:])] + ans["valid_ids"].append(arg["id"]) + ans["arguments"][arg["id"]] = rec + return ans + +def consistency(): + ans = {"sets": {}, "unsatisfiable_ids": []} + for s in load("sentence_sets.json"): + sents = [to_rpn(x) for x in s["sentences"]] + atoms = letters(sents); rows = all_rows(atoms) + truth = [[run(x, v) for x in sents] for v in rows] + models = [v for v, t in zip(rows, truth) if all(t)] + rec = {"satisfiable": bool(models), "models": len(models), "most_true_together": max(sum(t) for t in truth), + "valuation": models[0] if models else None} + if models: + rec["forced_true"] = [a for a in atoms if all(m[a] for m in models)] + rec["forced_false"] = [a for a in atoms if not any(m[a] for m in models)] + else: + rec["restoring"] = [i + 1 for i in range(len(sents)) if any(all(t[:i] + t[i + 1:]) for t in truth)] + ans["unsatisfiable_ids"].append(s["id"]) + ans["sets"][s["id"]] = rec + return ans + +def lit(atom, positive): + return atom if positive else "~" + atom + +def equivalence(): + ans = {"pairs": {}, "equivalent_ids": []} + for p in load("pairs.json"): + left, right = to_rpn(p["left"]), to_rpn(p["right"]) + rows = all_rows(letters([left, right])) + l_only = [v for v in rows if run(left, v) and not run(right, v)] + r_only = [v for v in rows if run(right, v) and not run(left, v)] + same = not l_only and not r_only + ans["pairs"][p["id"]] = { + "equivalent": same, "left_models": sum(1 for v in rows if run(left, v)), "right_models": sum(1 for v in rows if run(right, v)), + "left_only_rows": len(l_only), + "relation": "equivalent" if same else "left-entails-right" if not l_only else "right-entails-left" if not r_only else "neither", + "distinguishing": None if same else (l_only + r_only)[0]} + if same: ans["equivalent_ids"].append(p["id"]) + if os.path.exists("convert.json"): + ans["cnf"], ans["dnf"] = {}, {} + for c in load("convert.json"): + f = to_rpn(c["formula"]); atoms = letters([f]); rows = all_rows(atoms) + # one clause per false row (the clause is false in exactly that row); one term per true row + clauses = ["(" + " | ".join(lit(a, not v[a]) for a in atoms) + ")" for v in rows if not run(f, v)] + terms = ["(" + " & ".join(lit(a, v[a]) for a in atoms) + ")" for v in rows if run(f, v)] + ans["cnf"][c["id"]] = " & ".join(clauses) + ans["dnf"][c["id"]] = " | ".join(terms) + return ans + +def main(): + if os.path.exists("arguments.json"): answer = validity() + elif os.path.exists("sentence_sets.json"): answer = consistency() + else: answer = equivalence() + with open("answer.json", "w") as f: json.dump(answer, f, indent=1) + +if __name__ == "__main__": + main() diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/solution/solve.sh b/tasks/argument-check/argument-check-validity-d3-t0080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/task.toml b/tasks/argument-check/argument-check-validity-d3-t0080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5e8a0866e1c6f7af178fa05f4cab66e062eea395 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "argument-check" +tags = ["argument-check", "validity", "isced-0223", "train"] +isced_f = "0223" +family = "validity" +split = "train" +seed = 80 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/tests/checks.json b/tasks/argument-check/argument-check-validity-d3-t0080/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..50e70d33226edb08b8c2dcb90600c20a63fc5094 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/tests/checks.json @@ -0,0 +1,282 @@ +[ + { + "path": "arguments.ARG01.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.premise_true_rows", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "arguments.ARG01.counterexample_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG01", + "premises": [ + "E|(L->M)", + "P | G", + "(~L | ~P) -> M" + ], + "conclusion": "M -> P" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG02.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG03.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG03.counterexample_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG03", + "premises": [ + "~(G & M)", + "~G & M", + "E -> M" + ], + "conclusion": "~E <-> H" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.premise_true_rows", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "arguments.ARG04.counterexample_rows", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG04", + "premises": [ + "(L&E)|(~H<->G)", + "E|~G", + "~L & E -> M -> P", + "~M" + ], + "conclusion": "L | M" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG05.essential_premises", + "type": "set", + "value": [ + 2, + 3 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG06.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.premise_true_rows", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG06.essential_premises", + "type": "set", + "value": [ + 1 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG07.valid", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.premise_true_rows", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "arguments.ARG07.counterexample_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "type": "custom", + "name": "counterexample", + "args": { + "id": "ARG07", + "premises": [ + "H -> ~G", + "~H", + "(~G <-> H) <-> ~M & L" + ], + "conclusion": "G" + }, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.premise_true_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG08.essential_premises", + "type": "set", + "value": [ + 1, + 2 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "arguments.ARG09.valid", + "type": "bool", + "value": true, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.premise_true_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.counterexample_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "arguments.ARG09.essential_premises", + "type": "set", + "value": [ + 2, + 4 + ], + "item": "int", + "weight": 1.0 + }, + { + "path": "valid_ids", + "type": "set", + "value": [ + "ARG02", + "ARG05", + "ARG06", + "ARG08", + "ARG09" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/tests/test.sh b/tasks/argument-check/argument-check-validity-d3-t0080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/tests/validators.py b/tasks/argument-check/argument-check-validity-d3-t0080/tests/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..8d161e2765656acf1754813ff29079a40fe8a858 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/tests/validators.py @@ -0,0 +1,152 @@ +"""Custom checks for Argument Check. Standalone, standard library only. + +Every function reads the candidate from the answer, evaluates the formulas of the problem itself +(the formulas arrive in `args` as text) and returns True only if the candidate really has the +property asked for. Nothing is compared with a stored solution. Malformed answers return False. +""" + +_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4} +_MAX_LEN = 2000 + +class _Bad(Exception): + pass + +def _scan(text): + if not isinstance(text, str): raise _Bad() + toks, i, n = [], 0, len(text) + while i < n: + c = text[i] + if c == " " or c == "\t": i += 1 + elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3 + elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2 + elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1 + elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1 + else: raise _Bad() + return toks + +def _read(text): + """Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y).""" + toks = _scan(text) + state = {"i": 0} + def primary(): + i = state["i"] + if i >= len(toks): raise _Bad() + t = toks[i]; state["i"] = i + 1 + if t == "~": return ("not", primary()) + if t == "(": + x = climb(1) + if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad() + state["i"] += 1 + return x + if len(t) == 1 and t.isalpha(): return ("atom", t) + raise _Bad() + def climb(min_level): + left = primary() + while state["i"] < len(toks): + op = toks[state["i"]] + lv = _LEVEL.get(op) + if lv is None or lv < min_level: break + state["i"] += 1 + # & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right + right = climb(lv if op in ("->", "<->") else lv + 1) + left = ("bin", op, left, right) + return left + tree = climb(1) + if state["i"] != len(toks): raise _Bad() + return tree + +def _value(t, v): + kind = t[0] + if kind == "atom": return v[t[1]] + if kind == "not": return not _value(t[1], v) + op, x, y = t[1], _value(t[2], v), _value(t[3], v) + if op == "&": return x and y + if op == "|": return x or y + if op == "->": return y or not x + return x is y + +def _atoms(trees): + found, stack = set(), list(trees) + while stack: + t = stack.pop() + if t[0] == "atom": found.add(t[1]) + elif t[0] == "not": stack.append(t[1]) + else: stack.append(t[2]); stack.append(t[3]) + return found + +def _valuation(obj, atoms): + """The candidate must be an object with exactly the atoms that occur as keys and booleans as values.""" + if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None + for k in obj: + if obj[k] is not True and obj[k] is not False: return None + return obj + +def _dig(answer, keys): + cur = answer + for k in keys: + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + +def counterexample(answer, args): + """answer.arguments..counterexample makes every premise true and the conclusion false.""" + try: + prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"]) + v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl])) + if v is None: return False + return all(_value(p, v) for p in prem) and not _value(concl, v) + except Exception: + return False + +def satisfying_valuation(answer, args): + """answer.sets..valuation makes every sentence of the set true.""" + try: + sents = [_read(s) for s in args["sentences"]] + v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents)) + if v is None: return False + return all(_value(s, v) for s in sents) + except Exception: + return False + +def distinguishing_valuation(answer, args): + """answer.pairs..distinguishing gives the two formulas different truth values.""" + try: + left, right = _read(args["left"]), _read(args["right"]) + v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right])) + if v is None: return False + return _value(left, v) is not _value(right, v) + except Exception: + return False + +def _flatten(t, op): + parts, stack = [], [t] + while stack: + x = stack.pop() + if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2]) + else: parts.append(x) + return parts + +def _is_literal(t): + return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom") + +def normal_form(answer, args): + """answer.. is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to + args.formula, built only from atoms of args.formula, and at most 2000 characters long.""" + try: + form = args["form"] + if form not in ("cnf", "dnf"): return False + text = _dig(answer, [form, args["id"]]) + if not isinstance(text, str) or len(text) > _MAX_LEN: return False + orig = _read(args["formula"]); cand = _read(text) + atoms = sorted(_atoms([orig])) + if not _atoms([cand]) <= set(atoms): return False + outer, inner = ("&", "|") if form == "cnf" else ("|", "&") + for part in _flatten(cand, outer): + for leaf in _flatten(part, inner): + if not _is_literal(leaf): return False + for k in range(2 ** len(atoms)): + v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms)) + if _value(orig, v) is not _value(cand, v): return False + return True + except Exception: + return False diff --git a/tasks/argument-check/argument-check-validity-d3-t0080/tests/verify.py b/tasks/argument-check/argument-check-validity-d3-t0080/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/argument-check/argument-check-validity-d3-t0080/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main()