File size: 15,377 Bytes
1c34901
 
 
 
 
 
 
92c7a21
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
 
92c7a21
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c7a21
 
 
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c7a21
 
1c34901
 
 
 
 
 
 
 
92c7a21
1c34901
 
 
 
 
92c7a21
 
 
 
1c34901
 
 
92c7a21
1c34901
 
92c7a21
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c7a21
 
 
 
 
1c34901
 
 
92c7a21
1c34901
92c7a21
 
 
 
 
1c34901
92c7a21
 
1c34901
 
92c7a21
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
92c7a21
1c34901
 
 
 
 
 
 
 
 
 
 
 
92c7a21
1c34901
 
92c7a21
1c34901
92c7a21
 
 
 
1c34901
 
 
 
 
 
 
 
 
 
 
 
 
92c7a21
1c34901
 
 
 
 
 
 
 
 
92c7a21
1c34901
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""Symbolic reasoner: FOL β†’ ASP (clingo) with provenance tracking.

Takes model output (regex-parsed FOL) and runs clingo to get:
  - answer  (True / False / Unknown)
  - proof   (derived_by atoms reconstructed into human-readable steps)

Usage:
    # Score translations saved by: scripts/evaluate.py --output-file ...
    python scripts/reason.py --eval-file outputs/eval_translation_full.jsonl
"""

import re
import sys
import json
import argparse
from pathlib import Path
from typing import Optional

import clingo

sys.path.append(str(Path(__file__).resolve().parents[1]))

from src.utils.fol_schema import Atom, FOLProgram, FOLValidationError, parse_program

# ---------------------------------------------------------------------------
# FOL β†’ ASP conversion
# ---------------------------------------------------------------------------

_FORALL_RE     = re.compile(r'forall\s+x\s+\((.+)\)', re.IGNORECASE)
_ATOM_RE       = re.compile(r'^(not\s+)?([A-Z][a-zA-Z]*)\(([^)]+)\)$')

# Matches one FOL statement on a line (for space-separated model output fallback)
_FOL_ATOM_RE = re.compile(
    r'forall\s+x\s+\([^()]*(?:\([^()]*\)[^()]*)*\)'
    r'|(?:not\s+)?[A-Z][a-zA-Z]*\([^)]+\)'
    r'(?:\s*->\s*(?:not\s+)?[A-Z][a-zA-Z]*\([^)]+\))?'
)


def _asp_pred(name: str) -> str:
    return name.lower()


def _asp_arg(arg: str) -> str:
    arg = arg.strip()
    return arg.upper() if arg == 'x' else arg.lower().replace(' ', '_')


def _atom_to_asp(atom: Atom, negated: Optional[bool] = None) -> str:
    neg = atom.negated if negated is None else negated
    a = ','.join(_asp_arg(x) for x in atom.args)
    return ('-' if neg else '') + f'{_asp_pred(atom.predicate)}({a})'


_ASP_ATOM_RE = re.compile(r'^(-?)([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$')


def _parse_asp_atom(atom: str) -> tuple[str, list[str]]:
    """Parse 'pred(a,b)' or '-pred(a,b)' β†’ (full_pred_with_sign, [args])."""
    m = _ASP_ATOM_RE.match(atom.strip())
    if not m:
        return atom.strip(), []
    sign, pred, args_str = m.group(1), m.group(2), m.group(3)
    return sign + pred, [a.strip() for a in args_str.split(',')]


def _unify(goal: str, template: str) -> Optional[dict[str, str]]:
    """Try to unify a ground goal atom with a (possibly variadic) template.

    ProofWriter uses a single variable X (uppercase). Returns substitution
    {var: val} on success, None on failure.
    """
    g_pred, g_args = _parse_asp_atom(goal)
    t_pred, t_args = _parse_asp_atom(template)
    if g_pred != t_pred or len(g_args) != len(t_args):
        return None
    bindings: dict[str, str] = {}
    for g_a, t_a in zip(g_args, t_args):
        if t_a.isupper():           # variable
            if t_a in bindings and bindings[t_a] != g_a:
                return None         # conflict
            bindings[t_a] = g_a
        elif t_a != g_a:
            return None             # constant mismatch
    return bindings


def _apply_subst(atom: str, bindings: dict[str, str]) -> str:
    """Replace every variable in atom with its bound value."""
    if not bindings:
        return atom
    pred, args = _parse_asp_atom(atom)
    if not args:
        return atom
    new_args = [bindings.get(a, a) if a.isupper() else a for a in args]
    sign = '-' if pred.startswith('-') else ''
    bare_pred = pred.lstrip('-')
    return f'{sign}{bare_pred}({",".join(new_args)})'


def _is_valid_stmt(s: str) -> bool:
    s = s.strip()
    return bool(s) and (
        _FORALL_RE.match(s)
        or '->' in s
        or bool(_ATOM_RE.match(s))
        or (s.startswith('not ') and bool(_ATOM_RE.match(s[4:].strip())))
    )


def _extract_statements(raw: str) -> list[str]:
    """Split a raw FOL section into individual statements.

    Prefers newline split (gold data); falls back to regex tokenisation
    (model output, space-separated on one line).
    """
    by_line = [ln.strip() for ln in raw.split('\n') if ln.strip()]
    # If multiple valid lines β†’ use them (gold/newline format)
    if sum(1 for l in by_line if _is_valid_stmt(l)) > 1:
        return [ln for ln in by_line if _is_valid_stmt(ln)]
    # Fall back to regex token scan (space-separated model output)
    return [m.strip() for m in _FOL_ATOM_RE.findall(raw) if m.strip()]


def _extract_between(text: str, start: str, end: str) -> str:
    if start not in text or end not in text:
        return ''
    return text.split(start, 1)[1].split(end, 1)[0]


def parse_logic(logic: str) -> dict:
    """Parse a logic string (gold or model output) into premises + question.

    Unlike evaluate.parse_output, this correctly handles ground conjunctive rules
    (A and B -> C) by preferring newline split over regex atom scan.
    """
    prem_raw  = _extract_between(logic, '<extra_id_1>', '<extra_id_2>')
    q_raw     = _extract_between(logic, '<extra_id_2>', '<extra_id_3>')

    premises = _extract_statements(prem_raw)
    question = q_raw.strip().split('\n')[0].strip()  # first line only

    return {'premises_fol': premises, 'question_fol': question}


def fol_to_asp(program: FOLProgram):
    """Convert a validated FOL program to an ASP program.

    Returns:
        asp_program   β€” full ASP string
        rule_names    β€” {rule_id: human-readable FOL string}
        goal_atom     β€” ASP goal atom (positive form, for querying stable model)
        rule_structs  β€” list of (head_asp, body_asp_list, rid) for backward tracing
        base_facts    β€” set of base fact ASP strings (no trailing dot)
    """
    facts_asp    = [_atom_to_asp(f) + '.' for f in program.facts]
    rules_asp    = []
    prov_asp     = []
    rule_names   = {}
    rule_structs = []  # (head_asp, [body_atoms], rid)

    for i, rule in enumerate(program.rules, 1):
        rid      = f'rule{i}'
        head_asp = _atom_to_asp(rule.head)
        body_asp = [_atom_to_asp(b) for b in rule.body]
        rules_asp.append(f'{head_asp} :- {", ".join(body_asp)}.')
        for ba in body_asp:
            prov_asp.append(f'derived_by({head_asp},{ba},{rid}) :- {", ".join(body_asp)}.')
        rule_names[rid] = rule.to_fol()
        rule_structs.append((head_asp, body_asp, rid))

    # Positive form only β€” question negation is handled by the caller
    goal_atom = _atom_to_asp(program.question, negated=False)

    asp_program = (
        '\n'.join(facts_asp) + '\n'
        + '\n'.join(rules_asp) + '\n'
        + '\n'.join(prov_asp) + '\n'
    )
    base_facts = {f[:-1] for f in facts_asp}  # strip trailing '.'

    return asp_program, rule_names, goal_atom, rule_structs, base_facts


# ---------------------------------------------------------------------------
# Clingo reasoning
# ---------------------------------------------------------------------------

def _run_clingo(asp_program: str, goal_atom: str, negated_question: bool,
                rule_structs=None, base_facts=None) -> tuple[str, list[str]]:
    """Run clingo and return (answer, proof_steps).

    answer: 'True' / 'False' / 'Unknown'
    proof_steps: list of human-readable derivation steps
    """
    ctl = clingo.Control(['--warn=none'])
    ctl.add('base', [], asp_program)
    ctl.ground([('base', [])])

    model_atoms = set()
    with ctl.solve(yield_=True) as handle:
        for model in handle:
            for sym in model.symbols(atoms=True):
                model_atoms.add(str(sym))

    # OWA semantics: True/False require explicit derivation; else Unknown.
    #   Positive question Pred(args):  True if goal_atom derived, False if -goal_atom derived
    #   Negated question  not Pred:    True if -goal_atom derived, False if goal_atom derived
    if goal_atom:
        pos_holds = goal_atom in model_atoms
        neg_holds = ('-' + goal_atom) in model_atoms
        if not negated_question:
            if pos_holds:
                answer = 'True'
            elif neg_holds:
                answer = 'False'
            else:
                answer = 'Unknown'
        else:
            if neg_holds:
                answer = 'True'
            elif pos_holds:
                answer = 'False'
            else:
                answer = 'Unknown'
    else:
        answer = 'Unknown'

    # Build dependency graph from derived_by atoms:
    # deps[conclusion] = [(all_premises_for_this_rule, ruleid), ...]
    deps: dict[str, list[tuple[list[str], str]]] = {}
    by_conc_rule: dict[tuple[str, str], list[str]] = {}
    for pa in model_atoms:
        if not pa.startswith('derived_by('):
            continue
        inner = pa[len('derived_by('):-1]
        parts = _split_derived_by(inner)
        if len(parts) == 3:
            conc, prem, rid = parts
            key = (conc, rid)
            if key not in by_conc_rule:
                by_conc_rule[key] = []
            by_conc_rule[key].append(prem)

    for (conc, rid), prems in by_conc_rule.items():
        deps.setdefault(conc, []).append((prems, rid))

    # Backward chain from goal target to collect only relevant steps
    proof_target = ('-' + goal_atom) if (answer == 'True' and negated_question) or \
                                        (answer == 'False' and not negated_question) else goal_atom
    proof_steps = []

    if answer == 'Unknown':
        # Trace what would be needed and where the chain breaks
        proof_steps = _trace_unknown(goal_atom, model_atoms, rule_structs or [], base_facts or set())
    elif proof_target and proof_target in deps:
        visited: set[str] = set()
        queue = [proof_target]
        while queue:
            atom = queue.pop(0)
            if atom in visited:
                continue
            visited.add(atom)
            for prems, rid in deps.get(atom, []):
                prems_str = ' and '.join(prems)
                proof_steps.append(f'{prems_str} + {rid} -> therefore {atom}')
                queue.extend(prems)
        proof_steps.reverse()   # backward BFS β†’ flip to forward (cause before effect)
    elif answer in ('True', 'False') and proof_target and proof_target not in deps:
        proof_steps = [f'(base fact) {proof_target}']

    return answer, proof_steps


def _trace_unknown(goal: str, model_atoms: set, rule_structs: list, base_facts: set,
                   depth: int = 0, visited: set = None) -> list[str]:
    """Backward-trace a goal that cannot be derived, showing where the chain breaks.

    Uses proper unification so universal rules (with variable X) are only
    selected when their head actually matches the goal's argument pattern.
    """
    if visited is None:
        visited = set()
    if goal in visited or depth > 8:
        return []
    visited.add(goal)

    if goal in model_atoms or goal in base_facts:
        return []   # already satisfied β€” no failure here

    # Find applicable rules via unification
    applicable = []
    for head_tmpl, body_tmpl, rid in rule_structs:
        bindings = _unify(goal, head_tmpl)
        if bindings is not None:
            bound_body = [_apply_subst(b, bindings) for b in body_tmpl]
            applicable.append((bound_body, rid))

    if not applicable:
        return [f'{goal} <- [no rule or base fact]']

    lines = []
    bound_body, rid = applicable[0]
    body_str = ' and '.join(bound_body)
    lines.append(f'{goal} <- {body_str} + {rid}')
    missing = [b for b in bound_body if b not in model_atoms and b not in base_facts]
    for m in missing:
        lines.extend(_trace_unknown(m, model_atoms, rule_structs, base_facts, depth + 1, visited))
    return lines


def _split_derived_by(inner: str) -> list[str]:
    """Split 'conclusion,premise,ruleid' respecting nested parens."""
    parts = []
    depth = 0
    buf = []
    for ch in inner:
        if ch == '(':
            depth += 1
            buf.append(ch)
        elif ch == ')':
            depth -= 1
            buf.append(ch)
        elif ch == ',' and depth == 0:
            parts.append(''.join(buf))
            buf = []
        else:
            buf.append(ch)
    if buf:
        parts.append(''.join(buf))
    return parts


# ---------------------------------------------------------------------------
# End-to-end pipeline
# ---------------------------------------------------------------------------

def reason(raw_output: str) -> dict:
    """Parse model output, validate it, and run clingo.

    answer is 'True' / 'False' / 'Unknown', or 'Invalid' when the FOL fails
    schema validation (details in 'errors').
    """
    parsed    = parse_logic(raw_output)
    premises  = parsed['premises_fol']
    question  = parsed['question_fol']
    result    = {'premises_fol': premises, 'question_fol': question}

    try:
        program = parse_program(premises, question)
    except FOLValidationError as e:
        return {**result, 'answer': 'Invalid', 'proof': [], 'errors': e.issues,
                'warnings': [], 'asp_program': ''}

    asp_program, rule_names, goal_atom, rule_structs, base_facts = fol_to_asp(program)
    answer, proof = _run_clingo(asp_program, goal_atom, program.question.negated,
                                rule_structs=rule_structs, base_facts=base_facts)

    return {**result, 'answer': answer, 'proof': proof, 'errors': [],
            'warnings': program.warnings(), 'asp_program': asp_program}


# ---------------------------------------------------------------------------
# Evaluation on existing eval JSONL
# ---------------------------------------------------------------------------

def evaluate_eval_file(eval_file: str, max_samples: int = 0, verbose: bool = False):
    lines = Path(eval_file).read_text().strip().splitlines()
    if max_samples:
        lines = lines[:max_samples]

    correct = 0
    invalid = 0
    clingo_fail = 0
    total = len(lines)

    for i, line in enumerate(lines):
        d = json.loads(line)
        raw = d.get('raw_output', '')
        gold = d.get('gold_answer', '').strip()

        try:
            result = reason(raw)
        except Exception as e:
            clingo_fail += 1
            result = {'answer': 'Unknown'}
            if verbose:
                print(f'[{i}] CLINGO ERROR: {e}')
        pred = result['answer']

        if pred == 'Invalid':
            invalid += 1
            if verbose:
                print(f'[{i}] INVALID: {result["errors"]}')

        ok = pred.lower() == gold.lower()
        if ok:
            correct += 1

        if verbose or (not ok and i < 20):
            print(f'[{i}] gold={gold} pred={pred} {"OK" if ok else "FAIL"}')
            if result.get('proof'):
                for step in result['proof']:
                    print(f'     {step}')

    print(f'\n=== Results ({total} samples) ===')
    print(f'Answer accuracy : {correct}/{total} = {100*correct/total:.1f}%')
    print(f'Schema valid    : {total - invalid}/{total} = {100*(total - invalid)/total:.1f}%')
    print(f'Clingo errors   : {clingo_fail}')


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--eval-file', default='outputs/eval_translation_full.jsonl')
    parser.add_argument('--max-samples', type=int, default=0)
    parser.add_argument('--verbose', action='store_true')
    args = parser.parse_args()

    evaluate_eval_file(args.eval_file, args.max_samples, args.verbose)


if __name__ == '__main__':
    main()