File size: 6,928 Bytes
17cb132 | 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 | """mode3_verify.py -- the mode-3 answer verifier (single source of truth).
Strong comparator: LaTeX-normalization layer + sympy-exact equality, with a
float tolerance fallback and exact-string matching for word answers.
Returns True (verified match), False (verified mismatch), None (genuinely
ambiguous -- the caller must treat this as "not certifiable").
Unit checks live in __main__; run: python3 mode3_verify.py
"""
import re
from fractions import Fraction # noqa: F401 (kept for clarity)
import sympy as sp
_SPACING_TOKENS = ("\\left", "\\right", "\\!", "\\,", "\\;", "\\quad", "\\qquad")
_WRAPPER = re.compile(r"\\(?:text|boxed)\{([^{}]*)\}")
_MIXED_NUMBER = re.compile(r"([+-]?\d+)(\\[dt]?frac\{([^{}]*)\}\{([^{}]*)\})")
_BRACED_FRACTION = re.compile(r"\\[dt]?frac\{([^{}]*)\}\{([^{}]*)\}")
_DEGREE = re.compile(r"\^?\s*\{\s*\\circ\s*\}|\^?\\circ|°|\bdegrees?\b")
_POW_BRACED = re.compile(r"\^\{([^{}]*)\}")
_FUNCTION_BRACE = re.compile(r"([a-zA-Z]+)\{([^{}]*)\}")
_SYMBOL_MAP = {
"\\pi": "pi",
"\\sqrt": "sqrt",
"\\cdot": "*",
"\\times": "*",
"\\div": "/",
"\\pm": "±",
"\\infty": "oo",
"\\ell": "l",
}
_THOUSAND_COMMA = re.compile(r"(?<=\d),(?=\d)")
_IMAG_LOWER = re.compile(r"(?<=\d)i")
_IMAG_IMPLICIT_MUL = re.compile(r"(?<=\d)I")
_TOLERANCE = 1e-9
def normalize_latex(value) -> str:
"""Reduce LaTeX/plain text to a sympify-able or string-comparable form."""
text = str(value).strip()
if not text:
return ""
text = text.replace("$", "")
for token in _SPACING_TOKENS:
text = text.replace(token, "")
# unwrap \text{...} and \boxed{...} wrappers (repeat for nesting)
while True:
unwrapped = _WRAPPER.sub(r"\1", text)
if unwrapped == text:
break
text = unwrapped
# mixed numbers: 3\frac{1}{2} -> 3 + (1/2)
while True:
mixed = _MIXED_NUMBER.sub(lambda m: f"{m.group(1)} + ({m.group(3)}/{m.group(4)})", text)
if mixed == text:
break
text = mixed
# \frac{a}{b} -> (a/b), innermost first (loop handles nesting)
while True:
frac = _BRACED_FRACTION.sub(r"(\1/\2)", text)
if frac == text:
break
text = frac
# degree markers removed before any power handling
text = _DEGREE.sub("", text)
for token, replacement in _SYMBOL_MAP.items():
text = text.replace(token, replacement)
text = _POW_BRACED.sub(r"**(\1)", text)
text = text.replace("^", "**")
text = _FUNCTION_BRACE.sub(r"\1(\2)", text)
# imaginary unit: 6-5i -> 6-5I -> 6-5*I
text = _IMAG_LOWER.sub("I", text)
text = _IMAG_IMPLICIT_MUL.sub("*I", text)
text = _THOUSAND_COMMA.sub("", text)
text = re.sub(r"\s+", "", text)
# AIME-style leading zeros: 025 -> 25 (keep 0, 0.5, and 0x intact)
text = re.sub(r"^0+(?=\d)", "", text)
return text
def _to_expr(text: str):
"""sympy expression or None; ± is resolved by trying both branches."""
if not text:
return None
candidates = [text]
if "±" in text:
candidates = [text.replace("±", "+"), text.replace("±", "-")]
for candidate in candidates:
try:
return sp.sympify(candidate)
except Exception:
continue
return None
def _pairwise_equal(left, right) -> bool | None:
"""Elementwise compare of sequences (root lists, tuples)."""
if len(left) != len(right):
return False
for a, b in zip(left, right):
verdict = strong_compare(a, b)
if verdict is not True:
return False
return True
def strong_compare(expected, result) -> bool | None:
"""True / False / None (unverifiable). Exact-first, tolerance fallback."""
if result is None:
return None
e_text = normalize_latex(expected)
r_text = normalize_latex(result)
if e_text == r_text and e_text:
return True
e_expr = _to_expr(e_text)
r_expr = _to_expr(r_text)
if e_expr is None or r_expr is None:
# word answers (e.g. \text{Evelyn}): exact string is the only authority
if e_expr is None and r_expr is None:
return e_text == r_text if (e_text and r_text) else None
return None
if isinstance(e_expr, (list, tuple, sp.Tuple)) or isinstance(r_expr, (list, tuple, sp.Tuple)):
if isinstance(e_expr, (list, tuple, sp.Tuple)) and isinstance(r_expr, (list, tuple, sp.Tuple)):
return _pairwise_equal(r_expr, e_expr)
return False
try:
diff = sp.simplify(r_expr - e_expr)
if diff == 0:
return True
if diff.is_number:
try:
cdiff = complex(diff)
except (OverflowError, ValueError, TypeError):
return False
if cdiff.imag != 0:
return False
try:
scale = max(1.0, abs(float(e_expr)))
except (OverflowError, ValueError, TypeError):
return False
return abs(cdiff.real) <= _TOLERANCE * scale
return False
except Exception:
return None
def robust_compare(expected_latex: str, result):
"""Backward-compatible name delegating to the authority."""
return strong_compare(expected_latex, result)
if __name__ == "__main__":
checks = [
("145^\\circ", "145", True, "degree LaTeX"),
("145°", "145", True, "degree symbol"),
("\\sqrt{51}", "sqrt(51)", True, "sqrt result string"),
("6 - 5i", "6 - 5*I", True, "imaginary i"),
("3\\frac{1}{2}", "7/2", True, "mixed number exact"),
("3\\frac{1}{2}", "3.5", True, "mixed number decimal"),
("\\frac{8}{3}", "8/3", True, "plain fraction"),
("\\pi", "pi", True, "pi"),
("\\left( 5 \\right)", "5", True, "left/right delimiters"),
("[1, 2]", "[1, 2]", True, "tuple compare"),
("\\text{Evelyn}", "Evelyn", True, "word answer"),
("\\boxed{28}", "28", True, "boxed wrapper"),
("0.1", "1/10", True, "float vs exact tolerance"),
("145^\\circ", "30", False, "wrong angle"),
("30", "29", False, "off-by-one"),
("5", "5i", False, "imaginary mismatch"),
("\\text{Evelyn}", "Bob", False, "wrong word"),
("[1, 2]", "[2, 1]", False, "ordered tuple mismatch"),
("\\sqrt{51}", "sqrt(50)", False, "wrong radical"),
]
failed = 0
for expected, result, want, label in checks:
got = strong_compare(expected, result)
status = "ok" if got is want else "FAIL"
if got is not want:
failed += 1
print(f"{status:4} | {label:30} | expected {want!s:5} got {got!s:5} | {expected!r} vs {result!r}")
ambiguous = strong_compare("\\sqrt{51}", None)
print(f"ok | None-result ambiguous | {ambiguous}")
assert failed == 0, f"{failed} unit checks failed"
assert ambiguous is None
print("mode3_verify: all unit checks pass")
|