"""What a user actually reads: the printed answer is read back and compared with the semantics. The renderer belongs to the trusted base, so these tests do not match the printed string against an expected string. They read the text the way a careful reader would, keeping only the precision the text itself promises, and ask three questions. Does the described set agree with an exact evaluation of the formula at the points the shown digits settle? Is every printed decimal within half of its last shown place of the root it stands for? Are two different roots ever printed alike, which would make an interval read as empty? A bare rational in the text is read as exact, because the renderer prints a root that way only when the root really is that rational, while a decimal written after a tilde is read as the root rounded to SHOWN_DIGITS significant digits with the trailing zeros of the rounding dropped. """ import re from fractions import Fraction as F from lgmath import answers, exact, parse_a DECIMAL_TEXT = re.compile(r"~(-?\d[\d.eE+-]*)") ROOT_TEXT = re.compile(r"^root\((.+) ; ~(-?\d[\d.eE+-]*)\)$") RATIONAL_TEXT = re.compile(r"^-?\d+(/\d+)?$") # Each case is read from the input language, solved exactly, printed, and then read back as text. SOLVED_CASES = ( "solve x^2 - 2 < 0 for x", "solve x^3 - x >= 0 for x", "solve x^2 - 2 = 0 for x", "solve 1000000000000*x - 1 = 0 for x", "solve x^2 + x - 1/1000000000000 = 0 for x", "solve (x - 1)*(x - 10000000000001/10000000000000) = 0 for x", "solve x^4 - 2000000000001*x^2 + 1000001000000000000 > 0 for x", "solve -x^2 + 4*x - 5 > 0 for x", "solve x^2 - 3*x + 2 = 0 for x", ) def half_place(text: str) -> F: """Half of the last place a reader has to allow for a printed decimal. The promise is SHOWN_DIGITS significant digits, or more when more digits are shown, so a rounded value keeps its promised precision even when the rounding ends in zeros that are not printed. """ head = text.split("e")[0].split("E")[0] shown = len(re.sub(r"\D", "", head).lstrip("0")) or 1 promised = max(answers.SHOWN_DIGITS, shown) magnitude = abs(F(text)) order = 0 while magnitude >= 10: magnitude = magnitude / 10 order += 1 while 0 < magnitude < 1: magnitude = magnitude * 10 order -= 1 places = promised - 1 - order unit = F(1, 10 ** places) if places > 0 else F(10 ** (-places)) return unit / 2 def read_bound(text: str): """A printed bound as a value plus the widest error a reader must allow, or None for infinity.""" text = text.strip() if text in ("+inf", "-inf"): return None match = ROOT_TEXT.match(text) if match: value = F(match.group(2)) return (value, half_place(match.group(2))) if RATIONAL_TEXT.match(text): return (F(text), F(0)) raise AssertionError("the printed bound %r cannot be read" % text) def split_bound_texts(printed: str): """The bound texts of the printed answer, left to right, infinities left out.""" texts = [] for piece in printed.split(" U "): if piece == "no real solution (empty set)": continue for item in piece.strip()[1:-1].split(", "): if item.strip() not in ("+inf", "-inf"): texts.append(item.strip()) return texts def read_runs(printed: str): """The runs of the printed answer as (left, left_closed, right, right_closed) with read bounds.""" if printed == "no real solution (empty set)": return [] runs = [] for piece in printed.split(" U "): piece = piece.strip() if piece.startswith("{") and piece.endswith("}"): for item in piece[1:-1].split(", "): value = read_bound(item) runs.append((value, True, value, True)) continue parts = piece[1:-1].split(", ") if len(parts) != 2: raise AssertionError("the printed piece %r cannot be read" % piece) left_closed = piece[0] == "[" right_closed = piece[-1] == "]" runs.append((read_bound(parts[0]), left_closed, read_bound(parts[1]), right_closed)) return runs def read_membership(runs, x: F): """True or False when the shown digits settle the point, None when they leave it open.""" for left, left_closed, right, right_closed in runs: if left is not None: gap = x - left[0] if left[1] > 0 and abs(gap) <= left[1]: return None if gap < 0 or (gap == 0 and not left_closed): continue if right is not None: gap = x - right[0] if right[1] > 0 and abs(gap) <= right[1]: return None if gap > 0 or (gap == 0 and not right_closed): continue return True return False def probe_points(runs): """Rationals around the printed bounds: on them the exact and the printed reading must agree.""" points = [F(0), F(1), F(-1), F(1, 2), F(-1, 2), F(3), F(-3)] for left, _left_closed, right, _right_closed in runs: for bound in (left, right): if bound is None: continue value, width = bound step = width if width > 0 else F(1, 1000) for factor in (-40, -3, -1, 0, 1, 3, 40): points.append(value + factor * step) return points def answer_of(text: str): body = parse_a.parse_problem(text)[1] table, truth = exact.exact_cell_truth(body, "x") return body, answers.set_answer("x", table, truth) def test_printed_text_selects_the_same_points_as_the_exact_evaluation(): for text in SOLVED_CASES: body, answer = answer_of(text) printed = answers.render(answer) runs = read_runs(printed) decided = 0 for point in probe_points(runs): shown = read_membership(runs, point) if shown is None: continue decided += 1 assert shown == exact.eval_formula(body, {"x": point}), "%s at %s of %s" % ( shown, point, printed) assert decided >= 5, "too few points decide %s" % printed def test_printed_decimal_is_within_half_its_last_place_of_the_root(): checked = 0 for text in SOLVED_CASES: _body, answer = answer_of(text) printed = answers.render(answer) product = [answers.parse_q(c) for c in answer["product"]] brackets = [] for ref in answer["roots"]: if "q" in ref: continue root = exact.Root(product, answers.parse_q(ref["lo"]), answers.parse_q(ref["hi"])) brackets.append(exact.refine(root, F(1, 10 ** 30))) for match in DECIMAL_TEXT.finditer(printed): shown = match.group(1) value = F(shown) close = [cell for cell in brackets if max(abs(value - cell.lo), abs(value - cell.hi)) <= half_place(shown)] assert len(close) == 1, "%s is not within half a place of exactly one root of %s" % ( shown, printed) checked += 1 assert checked >= 5, "too few printed decimals were checked: %d" % checked def bound_indexes(answer): """Which root each printed bound stands for, in the order the text prints them.""" indexes = [] for left, left_closed, right, right_closed in answer["runs"]: if left is not None and left == right and left_closed and right_closed: indexes.append(left) continue if left is not None: indexes.append(left) if right is not None: indexes.append(right) return indexes def test_different_roots_are_never_printed_alike(): for text in SOLVED_CASES: _body, answer = answer_of(text) printed = answers.render(answer) indexes = bound_indexes(answer) texts = split_bound_texts(printed) assert len(texts) == len(indexes), "the bounds of %s do not line up" % printed seen = {} for index, shown in zip(indexes, texts): if shown in seen and seen[shown] != index: raise AssertionError("roots %d and %d are both printed as %s in %s" % ( seen[shown], index, shown, printed)) seen[shown] = index distinct = len(set(indexes)) assert len(set(texts)) == distinct, "one printed form stands for two roots of %s" % printed def test_a_root_that_is_a_terminating_decimal_is_printed_exactly(): _body, answer = answer_of("solve 1000000000000*x - 1 = 0 for x") assert answers.render(answer) == "{1/1000000000000}" _body, answer = answer_of("solve (x - 1)*(x - 10000000000001/10000000000000) = 0 for x") printed = answers.render(answer) assert "~" not in printed, printed assert "10000000000001/10000000000000" in printed, printed def test_an_irrational_root_keeps_the_tilde_and_the_polynomial(): _body, answer = answer_of("solve x^2 - 2 = 0 for x") printed = answers.render(answer) assert printed.count("root(x^2 - 2 ; ~") == 2, printed assert "~-1.41421356237" in printed and "~1.41421356237" in printed, printed def test_a_printed_counterexample_refutes_the_statement(): body = parse_a.parse_problem("prove x^2 + 1 < 0")[1] table, truth = exact.exact_cell_truth(body, "x") counterexample = answers.counterexample_from_cells("x", table, truth) printed = answers.render({"type": "verdict", "verdict": "disproved", "counterexample": counterexample}) assert printed.startswith("FALSE (counterexample: x = ") value = F(printed[len("FALSE (counterexample: x = "):-1]) assert not exact.eval_formula(body, {"x": value}), "%s does not refute %s" % (value, printed)