File size: 19,420 Bytes
40d9d40 | 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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | """Exact grader for structured math answers (Loubna msg 1257): a SET or TUPLE of exact numbers, an INTERVAL / union of
intervals with exact endpoints, or an EXPRESSION in named variables. Builds on the single-number grader (grader.py):
same extraction/cleaning, same restricted parser and the same exact number equality (never a numeric tolerance).
grade(reference, submission, kind, variables="") -> (passed, reason)
grade_safe(...) same, in a memory-capped subprocess with a timeout (use this in verifiers)
kind (fixed per task, stated in the task instruction):
set {a, b, c}: order and repeats do not matter; braces optional
tuple (a, b, c): order matters; parentheses optional
interval [a, b), (-\\infty, c] \\cup [d, \\infty) ...: compared as SETS of reals (unions are merged exactly)
expression one expression in the listed variables (e.g. "n" or "a,b"): equal as functions, proved by exact
symbolic simplification to 0; random numeric evaluation can only reject
Numbers inside follow grader.py (exact values, functions only if the reference uses their family).
"""
import multiprocessing as mp
import random
import re
import sys
from pathlib import Path
import sympy
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import grader as G # noqa: E402
from grader import Reject # noqa: E402
__version__ = "1"
_orig_nonzero = G._nonzero
def _nonzero_sym(d):
"""Divisors with variables are allowed unless identically zero; numeric divisors keep grader.py's check."""
if getattr(d, "free_symbols", None):
if sympy.cancel(sympy.together(d)) == 0:
raise Reject("division by zero")
return d
return _orig_nonzero(d)
G._nonzero = _nonzero_sym
KINDS = ("set", "tuple", "interval", "expression")
MAX_ITEMS = 60
_INF = re.compile(r"^\s*([+-]?)\s*\\infty\s*$|^\s*([+-]?)\s*\\inf\s*$|^\s*([+-]?)\s*oo\s*$")
# ---------------------------------------------------------------- shared helpers
def _top_level_boxes(text: str):
out, i = [], 0
while True:
m = G._BOX.search(text, i)
if not m:
return out
depth, j = 1, m.end()
while j < len(text) and depth:
depth += {"{": 1, "}": -1}.get(text[j], 0)
j += 1
out.append(re.sub(r"\s+", "", text[m.end():j - 1]))
i = j
def _clean_struct(text: str) -> str:
"""grader.clean without its single-value wrapper stripping of commas; keeps \\{ \\} \\cup.
Several top-level boxes with different contents are a hedge: rejected (review 2026-11-24)."""
if len(set(_top_level_boxes(text or ""))) > 1:
raise Reject("several different boxed answers")
if len(text or "") > 20_000:
raise Reject("answer too long")
text = re.sub(r"\\\\(?=[A-Za-z{}])", r"\\", text) # shell-doubled backslashes: \\\\frac -> \\frac
t = G.clean(text)
# plain-text function names (agents often write ln(x), sin x): same as grader.clean does for sqrt( and pi
t = re.sub(r"(?<![\\A-Za-z])(arcsin|arccos|arctan|ln|log|sin|cos|tan|exp)(?![A-Za-z])", r"\\\1 ", t)
t = re.sub(r"\\lbrace|\\\{", "{", t)
t = re.sub(r"\\rbrace|\\\}", "}", t)
t = re.sub(r"\\(?:lbrack)", "[", t)
t = re.sub(r"\\(?:rbrack)", "]", t)
t = re.sub(r"\\(?:mathbb\{R\}|R)(?![A-Za-z])", "R", t)
return t.strip()
def _split_top(s: str, sep: str = ","):
out, depth, cur = [], 0, []
for ch in s:
if ch in "([{":
depth += 1
elif ch in ")]}":
depth -= 1
if depth < 0:
raise Reject("unbalanced brackets")
if ch == sep and depth == 0:
out.append("".join(cur)); cur = []
else:
cur.append(ch)
if depth != 0:
raise Reject("unbalanced brackets")
out.append("".join(cur))
return [x.strip() for x in out]
def _number(elem: str, allowed: set, is_reference: bool, labels: bool = True):
"""One exact real number (grader.py rules); also strips a leading 'x =' / 'x_1 =' unless labels=False."""
if not labels and re.match(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=", elem) and not is_reference:
raise Reject("labelled tuple components (write the tuple in the asked order, without names)")
e = re.sub(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*", "", elem.strip())
if not e:
raise Reject("empty element")
if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|%", e):
raise Reject("element is not a single exact number")
toks = G._mixed_numbers(G.tokenize(e, sci="e" not in allowed), is_reference)
v = G.Parser(toks, allowed).parse()
if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False:
raise Reject("non-finite value")
if v.is_real is False:
raise Reject("not a real number")
return v
def _strip_outer(t: str, pairs):
for a, b in pairs:
if t.startswith(a) and t.endswith(b):
inner = t[len(a):len(t) - len(b)]
try:
_split_top(inner) # the outer pair must enclose everything (not "(1,2),(3,4)")
except Reject:
continue
depth, ok = 0, True
for ch in inner:
depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(ch, 0)
if depth < 0:
ok = False
break
if ok:
return inner.strip(), True
return t, False
def _items(text: str, allowed: set, is_reference: bool, brackets, labels: bool = True):
t = _clean_struct(text)
if not t:
raise Reject("empty")
if len(t) > G.MAX_LEN * 2:
raise Reject("answer too long")
if re.search(r"\\(?:text|mbox)\{[^}]*[A-Za-z]{2,}|\b(?:or|and)\b", t) and not re.search(r"\\(?:text|mbox)\{\s*,?\s*\}", t):
raise Reject("words in the answer (write only the list)")
inner, _ = _strip_outer(t, brackets)
parts = _split_top(inner)
if len(parts) > MAX_ITEMS:
raise Reject("too many items")
if any(not p for p in parts):
raise Reject("empty item")
return [_number(p, allowed, is_reference, labels) for p in parts]
def _eq(a, b) -> bool:
try:
return G.exact_equal(a, b)
except Exception:
return False
def _dedup(vals):
out = []
for v in vals:
if not any(_eq(v, w) for w in out):
out.append(v)
return out
# ---------------------------------------------------------------- set / tuple
def grade_set(reference, submission, allowed):
g = _dedup(_items(reference, allowed, True, [("{", "}")]))
s = _dedup(_items(submission, allowed, False, [("{", "}")]))
if len(s) != len(g):
return False, f"wrong number of elements ({len(s)} vs {len(g)})"
left = list(g)
for v in s:
k = next((i for i, w in enumerate(left) if _eq(v, w)), None)
if k is None:
return False, "wrong element"
left.pop(k)
return True, "exact match"
def grade_tuple(reference, submission, allowed):
g = _items(reference, allowed, True, [("(", ")"), ("[", "]"), ("{", "}")])
s = _items(submission, allowed, False, [("(", ")"), ("[", "]")], labels=False)
if len(s) != len(g):
return False, f"wrong length ({len(s)} vs {len(g)})"
for v, w in zip(s, g):
if not _eq(v, w):
return False, "wrong component"
return True, "exact match"
# ---------------------------------------------------------------- intervals
def _endpoint(e, allowed, is_reference):
m = _INF.match(e)
if m:
sign = "".join(x for x in m.groups() if x)
return -sympy.oo if sign == "-" else sympy.oo
return _number(e, allowed, is_reference)
def _intervals(text, allowed, is_reference):
t = _clean_struct(text)
if not t:
raise Reject("empty")
t = re.sub(r"^\s*[A-Za-z]\s*\\in\s*", "", t) # "x \in [1,2)"
if re.fullmatch(r"R|\(-\\infty\s*,\s*\+?\\infty\)", t.replace(" ", "")):
return [(-sympy.oo, False, sympy.oo, False)]
pieces = [p.strip() for p in re.split(r"\\cup|∪|(?<![A-Za-z])U(?![A-Za-z])", t)]
out = []
for p in pieces:
if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]":
raise Reject("each piece must look like (a, b), [a, b], [a, b) or (a, b]")
parts = _split_top(p[1:-1])
if len(parts) != 2:
raise Reject("an interval needs exactly two endpoints")
lo, hi = _endpoint(parts[0], allowed, is_reference), _endpoint(parts[1], allowed, is_reference)
lc, hc = p[0] == "[", p[-1] == "]"
if (lo in (sympy.oo, -sympy.oo) and lc) or (hi in (sympy.oo, -sympy.oo) and hc):
raise Reject("infinite endpoint must be open")
if lo == sympy.oo or hi == -sympy.oo:
raise Reject("bad infinite endpoint")
out.append((lo, lc, hi, hc))
return out
def _num(v):
return float("inf") if v == sympy.oo else float("-inf") if v == -sympy.oo else float(sympy.N(v, 30))
def _cmp(a, b):
"""-1/0/1 exactly (0 only if PROVED equal)."""
if a in (sympy.oo, -sympy.oo) or b in (sympy.oo, -sympy.oo):
return 0 if a == b else (-1 if _num(a) < _num(b) else 1)
if _eq(a, b):
return 0
d = sympy.N(a - b, 60)
if not d.is_Number or d == 0:
raise Reject("cannot order interval endpoints")
return -1 if d < 0 else 1
def _normalize(ivs):
"""Drop empty pieces, sort, merge overlapping / touching pieces: a canonical union."""
keep = []
for lo, lc, hi, hc in ivs:
c = _cmp(lo, hi)
if c > 0 or (c == 0 and not (lc and hc)):
continue # empty piece
keep.append((lo, lc, hi, hc))
keep.sort(key=lambda x: (_num(x[0]), not x[1]))
out = []
for iv in keep:
if out:
lo, lc, hi, hc = out[-1]
c = _cmp(iv[0], hi)
if c < 0 or (c == 0 and (hc or iv[1])): # overlap, or touching with the shared point included
c2 = _cmp(iv[2], hi)
nhi, nhc = (iv[2], iv[3]) if c2 > 0 else (hi, hc or iv[3]) if c2 == 0 else (hi, hc)
out[-1] = (lo, lc, nhi, nhc)
continue
out.append(iv)
return out
def grade_interval(reference, submission, allowed):
g = _normalize(_intervals(reference, allowed, True))
s = _normalize(_intervals(submission, allowed, False))
if len(s) != len(g):
return False, "different set of reals"
for (a, ac, b, bc), (c, cc, d, dc) in zip(s, g):
if _cmp(a, c) != 0 or _cmp(b, d) != 0 or ac != cc or bc != dc:
return False, "different set of reals"
return True, "exact match"
# ---------------------------------------------------------------- expressions in variables
class VarParser(G.Parser):
"""grader.Parser plus named variables (single letters or greek commands) and symbolic exponents."""
def __init__(self, tokens, allowed, variables):
super().__init__(tokens, allowed)
# positive: AoPS variables are lengths, counts and indices (sqrt(a^2) = a); review 2026-11-24 item F
self.vars = {v: sympy.Symbol(v, real=True) for v in variables}
def term(self):
"""grader.Parser.term, but a number may follow ')', '}', ']' or a variable: (n+1)2^n, n2^n, 2^n3^n."""
v = self.unary()
while True:
k, s = self.peek()
if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")):
self.take(); v = v * self.unary()
elif (k, s) == ("sym", "/"):
self.take(); v = v / G._nonzero(self.unary())
elif self.starts_atom():
if k == "num":
pk, pv = self.t[self.i - 1][:2]
if not ((pk == "sym" and pv in ")}]") or (pk in ("let", "cmd") and pv in self.vars)):
raise Reject("two numbers side by side")
v = v * self.power()
else:
return v
def arg(self):
k, v = self.peek()
if k in ("let", "cmd") and v in self.vars: # \frac ab
return self.atom()
return super().arg()
def starts_atom(self):
k, v = self.peek()
return super().starts_atom() or ((k == "let" or k == "cmd") and v in self.vars)
def atom(self):
k, v = self.peek()
if (k == "let" or k == "cmd") and v in self.vars:
self.take()
if self.peek() == ("sym", "_"):
raise Reject("subscripts not supported")
return self.vars[v]
return super().atom()
def _pow(self, base, exp):
if exp.free_symbols or base.free_symbols:
if exp.is_Rational and abs(exp) > 60:
raise Reject("exponent too large")
if exp.free_symbols and base.free_symbols:
raise Reject("variable in base and exponent")
if base.free_symbols and exp.is_Rational and exp.q > 1:
return sympy.Pow(base, exp)
return sympy.Pow(base, exp)
return super()._pow(base, exp)
def _expr(text, allowed, variables, is_reference):
raw = G._last_top_level_box(G._normalize_unicode(text or "")) or (text or "")
m0 = re.match(r"^[\s$\\(\[]*([A-Za-z])\s*=", raw)
if m0 and m0.group(1) in variables:
raise Reject("an equation in the variable, not an expression")
if is_reference and (re.search(r"\\\{|\\lbrace|\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]|/\s*[A-Za-z]\s*[A-Za-z]", raw)):
raise Reject("ambiguous reference (braces, function of a product, or a/bc)")
t = _clean_struct(text)
m = re.match(r"^\s*([A-Za-z])(\([^()]*\))?(?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)", t) # "f(n) = ...", "S = ..."
if m:
if m.group(1) in variables and not m.group(2):
raise Reject("an equation in the variable, not an expression")
t = t[m.end():]
if is_reference and (re.search(r"\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]", t) or "{" in re.sub(r"\\[A-Za-z]+\s*\{|[\^_]\s*\{|\}\s*\{", "", t).replace("\\{", "{") and re.search(r"\\\{", t)
or re.search(r"/\s*[A-Za-z]\s*[A-Za-z]", t)):
raise Reject("ambiguous reference (function of a product, braces, or a/bc)")
if not t:
raise Reject("empty")
if len(t) > G.MAX_LEN:
raise Reject("answer too long")
if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|,|%|\\sum|\\prod|\\int|!", t):
raise Reject("not a single closed-form expression")
toks = G.tokenize(t, sci=False)
toks = [("sym", "_", "_") if x[0] == "sym" and x[1] == "_" else x for x in toks]
v = VarParser(toks, allowed, variables).parse()
if v.has(sympy.zoo, sympy.nan):
raise Reject("undefined value")
extra = {str(s) for s in v.free_symbols} - set(variables)
if extra:
raise Reject(f"unknown variables {sorted(extra)}")
return v
def _points(syms, rng, k=6):
"""Random rational points away from 0 and 1 (positive, so radicals and logs of the variables stay real)."""
return [{s: sympy.Rational(rng.randint(7, 97), rng.randint(3, 13)) for s in syms} for _ in range(k)]
def grade_expression(reference, submission, allowed, variables):
g = _expr(reference, allowed, variables, True)
s = _expr(submission, allowed, variables, False)
d = s - g
if d == 0:
return True, "exact match"
syms = sorted(d.free_symbols | g.free_symbols, key=str)
rng = random.Random(0)
for pt in _points(syms, rng):
try:
dv, gv = sympy.N(d.subs(pt), 40), sympy.N(g.subs(pt), 40)
except Exception:
continue
if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-25", 40) * max(1, abs(gv)):
return False, "different expression"
try: # equal up to a constant factor 1: a(sqrt6-sqrt2) = 2a sqrt(2-sqrt3)
q = sympy.cancel(sympy.together(s / g))
if not q.free_symbols and q.is_number and _eq(q, sympy.Integer(1)):
return True, "exact match"
except Exception:
pass
for cand in (lambda e: sympy.cancel(sympy.together(e)), sympy.radsimp, sympy.simplify,
lambda e: sympy.simplify(sympy.expand_log(sympy.expand_power_base(e, force=False)))):
try:
if cand(d) == 0:
return True, "exact match"
except Exception:
pass
return False, "could not prove the expressions equal"
# ---------------------------------------------------------------- entry points
def parse_variables(variables):
vs = [v.strip().lstrip("\\") for v in re.split(r"[,\s]+", variables or "") if v.strip()]
for v in vs:
if not re.fullmatch(r"[A-Za-z]|alpha|beta|gamma|theta|lambda|mu|phi|omega|rho|sigma|tau", v) or v in ("e", "i"):
raise Reject(f"unsupported variable name {v!r}")
return vs
def grade(reference: str, submission: str, kind: str, variables: str = ""):
if kind not in KINDS:
return False, f"unknown kind {kind!r}"
try:
ref_clean = _clean_struct(reference)
allowed = G.allowed_from_reference(ref_clean)
vs = parse_variables(variables) if kind == "expression" else []
if kind == "expression":
allowed.discard("e") if "e" in vs else None
except Reject as e:
return False, f"reference unusable: {e}"
try:
if kind == "set":
return grade_set(reference, submission, allowed)
if kind == "tuple":
return grade_tuple(reference, submission, allowed)
if kind == "interval":
return grade_interval(reference, submission, allowed)
return grade_expression(reference, submission, allowed, vs)
except Reject as e:
return False, f"format: {e}"
except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError, AttributeError) as e:
return False, f"format: {type(e).__name__}"
except Exception as e:
return False, f"could not grade ({type(e).__name__})"
def check_reference(reference: str, kind: str, variables: str = ""):
"""Reference parses under the kind's rules and matches itself."""
return grade(reference, reference, kind, variables)
def _worker(q, *args):
try:
import resource
vm = 0
for line in open("/proc/self/status"):
if line.startswith("VmSize:"):
vm = int(line.split()[1]) * 1024
resource.setrlimit(resource.RLIMIT_AS, (vm + G.MEM_LIMIT, vm + G.MEM_LIMIT))
except Exception:
pass
try:
q.put(grade(*args))
except MemoryError:
q.put((False, "grader out of memory"))
except Exception as e:
q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, kind: str, variables: str = "", timeout: float = 20.0):
ctx = mp.get_context("fork")
q = ctx.Queue()
p = ctx.Process(target=_worker, args=(q, reference, submission, kind, variables))
p.start(); p.join(timeout)
if p.is_alive():
p.kill(); p.join()
return False, "timeout"
try:
return q.get(timeout=1)
except Exception:
return False, "grader crashed"
|