"""Strict, exact single-number grader for Harbor math tasks (v2). Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8, \\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations. grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers) How it works - Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly. - Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2). - Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails. """ import multiprocessing as mp import re import unicodedata import sympy from sympy import Integer, Rational __version__ = "2" MAX_LEN = 1000 # characters of the cleaned answer MAX_INT_DIGITS = 1000 # digits of any number literal MAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notation MAX_POW_BITS = 100_000 # estimated size of an exact power before computing it MEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes) FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp} FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}] TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan) _X, _T = sympy.Symbol("x"), sympy.Symbol("T") class Reject(Exception): pass # ---------------------------------------------------------------- extraction and cleaning _BOX = re.compile(r"\\(?:boxed|fbox)\s*\{") _SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-") _DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d" def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t) def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})" _NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I) _UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$") _UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$") _DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$") _LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)") def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(? \sqrt(2) t = re.sub(r"(? \pi/4 return re.sub(r"\s+", " ", t).strip() # ---------------------------------------------------------------- parser TOKEN = re.compile(r"\s*(?:(?P\d+\.\d*|\.\d+|\d+)(?:[eE](?P[+-]?\d+))?|(?P\\[A-Za-z]+)|(?P[-+*/^(){}\[\]])|(?P[A-Za-z]))") NUM_ONLY = re.compile(r"\s*(?P\d+\.\d*|\.\d+|\d+)") def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1 class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg""" def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None) def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed) def term(self): 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 / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power() def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp) def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument") def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed") def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(? MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, 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 _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL) def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value") def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) 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, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) 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"