Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
mathematics
formal-verification
symbolic-algebra
theorem-proving
multi-agent-systems
benchmark
Download lgmath/parse_a.py from tailot/lingologos-math: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/tailot/lingologos-math/resolve/main/lgmath/parse_a.py
- Command line
-
hf download hf://datasets/tailot/lingologos-math/lgmath/parse_a.py
-
curl -L -o parse_a.py https://huggingface.co/datasets/tailot/lingologos-math/resolve/main/lgmath/parse_a.py
11.3 kB
| """Formalizer A parser: a hand written tokenizer plus recursive descent with backtracking. | |
| Grammar of the math language (lowest precedence first):: | |
| problem := 'evaluate' term | 'prove' formula ['over' 'Z'] | 'solve' formula 'for' IDENT (',' IDENT)* ['over' 'Z'] | |
| | ('derivative' | 'antiderivative') term ['wrt' IDENT] | 'integral' term 'from' term 'to' term ['wrt' IDENT] | |
| | ('maximize' | 'minimize') term 'subject' 'to' formula | |
| | ('det' | 'rank' | 'inverse' | 'nullspace') matrix | ('linsolve') matrix vector | |
| | 'product' matrix matrix | 'power' matrix term | |
| formula := imp ('<=>' imp)* left associative | |
| imp := or ('=>' imp)? right associative | |
| or := and ('or' and)* | |
| and := not ('and' not)* | |
| not := 'not' not | atom | |
| atom := 'true' | 'false' | quantifier | '(' formula ')' | term (relop term)+ | |
| quantifier := ('forall' | 'exists') IDENT ['in' ('R' | 'Z')] '.' formula | |
| term := sum of products ('*', '/', 'mod', 'div'); unary minus binds weaker than '^' (-x^2 = -(x^2)) | |
| atom also: term '|' term (divisibility) | |
| """ | |
| import re | |
| from fractions import Fraction | |
| from typing import List, Optional, Tuple | |
| from .tree import KEYWORDS, Node, ParseError, UnsupportedError, check_input_text | |
| _TOKEN = re.compile( | |
| r"\s*(?:(?P<num>\d+\.\d+|\d+)|(?P<id>[A-Za-z_][A-Za-z_0-9]*)|(?P<op><=>|=>|<=|>=|!=|[-+*/^()<>=.\[\],|]))" | |
| ) | |
| _REL = {"=": "eq", "!=": "ne", "<": "lt", "<=": "le", ">": "gt", ">=": "ge", "|": "dvd"} | |
| def tokenize(text: str) -> List[Tuple[str, str]]: | |
| tokens: List[Tuple[str, str]] = [] | |
| pos = 0 | |
| text = text.rstrip() | |
| while pos < len(text): | |
| match = _TOKEN.match(text, pos) | |
| if match is None: | |
| raise ParseError("unexpected character %r at position %d" % (text[pos:].lstrip()[:1], pos)) | |
| pos = match.end() | |
| if match.group("num") is not None: | |
| tokens.append(("num", match.group("num"))) | |
| elif match.group("id") is not None: | |
| word = match.group("id") | |
| tokens.append(("kw" if word in KEYWORDS else "id", word)) | |
| else: | |
| tokens.append(("op", match.group("op"))) | |
| return tokens | |
| class _Parser: | |
| def __init__(self, tokens: List[Tuple[str, str]]): | |
| self.tokens = tokens | |
| self.pos = 0 | |
| # -- token helpers ------------------------------------------------- | |
| def peek(self) -> Tuple[str, str]: | |
| return self.tokens[self.pos] if self.pos < len(self.tokens) else ("end", "") | |
| def take(self) -> Tuple[str, str]: | |
| token = self.peek() | |
| self.pos += 1 | |
| return token | |
| def at(self, kind: str, value: str) -> bool: | |
| return self.peek() == (kind, value) | |
| def expect(self, kind: str, value: str) -> None: | |
| if not self.at(kind, value): | |
| raise ParseError("expected %r but found %r" % (value, self.peek()[1] or "end of input")) | |
| self.pos += 1 | |
| # -- problems ------------------------------------------------------ | |
| def problem(self) -> Node: | |
| kind, value = self.take() | |
| if kind != "kw": | |
| raise ParseError("a problem starts with a command word such as evaluate, prove or solve") | |
| if value == "evaluate": | |
| node: Node = ("evaluate", self.term()) | |
| elif value == "prove": | |
| body = self.formula() | |
| node = ("prove", body) | |
| if self.at("kw", "over"): | |
| self.take() | |
| self.domain_z() | |
| node = ("provez", body) | |
| elif value == "solve": | |
| body = self.formula() | |
| self.expect("kw", "for") | |
| names = [self.ident("a variable name must follow 'for'")] | |
| while self.at("op", ","): | |
| self.take() | |
| names.append(self.ident("a variable name must follow ','")) | |
| over_z = False | |
| if self.at("kw", "over"): | |
| self.take() | |
| self.domain_z() | |
| over_z = True | |
| if over_z and len(names) > 1: | |
| raise UnsupportedError("integer systems are not supported") | |
| if len(names) > 1: | |
| node = ("solvesys", body, ("names",) + tuple(names)) | |
| else: | |
| node = ("solvez" if over_z else "solve", body, names[0]) | |
| elif value in ("derivative", "antiderivative"): | |
| body = self.term() | |
| node = (value, body, self.optional_wrt()) | |
| elif value == "integral": | |
| body = self.term() | |
| self.expect("kw", "from") | |
| low = self.term() | |
| self.expect("kw", "to") | |
| high = self.term() | |
| node = ("integral", body, self.optional_wrt(), low, high) | |
| elif value in ("maximize", "minimize"): | |
| objective = self.term() | |
| self.expect("kw", "subject") | |
| self.expect("kw", "to") | |
| node = ("optimize", value[:3], objective, self.formula()) | |
| elif value in ("det", "rank", "inverse", "nullspace"): | |
| node = (value, self.matrix()) | |
| elif value == "linsolve": | |
| node = (value, self.matrix(), self.vector()) | |
| elif value == "product": | |
| node = (value, self.matrix(), self.matrix()) | |
| elif value == "power": | |
| node = (value, self.matrix(), self.term()) | |
| else: | |
| raise ParseError("a problem starts with a command word such as evaluate, prove or solve") | |
| if self.peek()[0] != "end": | |
| raise ParseError("unexpected trailing input %r" % self.peek()[1]) | |
| return node | |
| def ident(self, message: str) -> str: | |
| kind, name = self.take() | |
| if kind != "id": | |
| raise ParseError(message) | |
| return name | |
| def domain_z(self) -> None: | |
| if self.take() != ("id", "Z"): | |
| raise ParseError("only the domain Z may follow 'over'") | |
| def optional_wrt(self) -> Optional[str]: | |
| if self.at("kw", "wrt"): | |
| self.take() | |
| return self.ident("a variable name must follow 'wrt'") | |
| return None | |
| def matrix(self) -> Node: | |
| self.expect("op", "[") | |
| rows = [] | |
| while True: | |
| self.expect("op", "[") | |
| entries = [self.term()] | |
| while self.at("op", ","): | |
| self.take() | |
| entries.append(self.term()) | |
| self.expect("op", "]") | |
| rows.append(("row",) + tuple(entries)) | |
| if self.at("op", ","): | |
| self.take() | |
| continue | |
| break | |
| self.expect("op", "]") | |
| if len({len(row) for row in rows}) != 1: | |
| raise ParseError("matrix rows must have the same length") | |
| return ("mat",) + tuple(rows) | |
| def vector(self) -> Node: | |
| self.expect("op", "[") | |
| entries = [self.term()] | |
| while self.at("op", ","): | |
| self.take() | |
| entries.append(self.term()) | |
| self.expect("op", "]") | |
| return ("vec",) + tuple(entries) | |
| # -- formulas ------------------------------------------------------ | |
| def formula(self) -> Node: | |
| left = self.imp() | |
| while self.at("op", "<=>"): | |
| self.take() | |
| left = ("iff", left, self.imp()) | |
| return left | |
| def imp(self) -> Node: | |
| left = self.or_() | |
| if self.at("op", "=>"): | |
| self.take() | |
| return ("imp", left, self.imp()) | |
| return left | |
| def or_(self) -> Node: | |
| left = self.and_() | |
| while self.at("kw", "or"): | |
| self.take() | |
| left = ("or", left, self.and_()) | |
| return left | |
| def and_(self) -> Node: | |
| left = self.not_() | |
| while self.at("kw", "and"): | |
| self.take() | |
| left = ("and", left, self.not_()) | |
| return left | |
| def not_(self) -> Node: | |
| if self.at("kw", "not"): | |
| self.take() | |
| return ("not", self.not_()) | |
| return self.atom() | |
| def atom(self) -> Node: | |
| kind, value = self.peek() | |
| if (kind, value) in (("kw", "true"), ("kw", "false")): | |
| self.take() | |
| return (value,) | |
| if (kind, value) in (("kw", "forall"), ("kw", "exists")): | |
| self.take() | |
| kind2, name = self.take() | |
| if kind2 != "id": | |
| raise ParseError("a variable name must follow the quantifier") | |
| domain = "R" | |
| if self.at("kw", "in"): | |
| self.take() | |
| token = self.take() | |
| if token not in (("id", "R"), ("id", "Z")): | |
| raise UnsupportedError("only the domains R and Z are supported") | |
| domain = token[1] | |
| self.expect("op", ".") | |
| return (value, name, domain, self.formula()) | |
| if (kind, value) == ("op", "("): | |
| saved = self.pos | |
| try: | |
| return self.relation() | |
| except ParseError: | |
| self.pos = saved | |
| self.take() | |
| inner = self.formula() | |
| self.expect("op", ")") | |
| return inner | |
| return self.relation() | |
| def relation(self) -> Node: | |
| terms = [self.term()] | |
| ops: List[str] = [] | |
| while self.peek()[0] == "op" and self.peek()[1] in _REL: | |
| ops.append(_REL[self.take()[1]]) | |
| terms.append(self.term()) | |
| if not ops: | |
| raise ParseError("a comparison operator is required") | |
| result: Node = (ops[0], terms[0], terms[1]) | |
| for index in range(1, len(ops)): | |
| result = ("and", result, (ops[index], terms[index], terms[index + 1])) | |
| return result | |
| # -- terms --------------------------------------------------------- | |
| def term(self) -> Node: | |
| left = self.product() | |
| while self.peek()[0] == "op" and self.peek()[1] in ("+", "-"): | |
| op = self.take()[1] | |
| left = ("add" if op == "+" else "sub", left, self.product()) | |
| return left | |
| def product(self) -> Node: | |
| left = self.unary() | |
| while (self.peek()[0] == "op" and self.peek()[1] in ("*", "/")) or self.peek() in (("kw", "mod"), ("kw", "div")): | |
| op = self.take()[1] | |
| left = ({"*": "mul", "/": "div", "mod": "mod", "div": "idiv"}[op], left, self.unary()) | |
| return left | |
| def unary(self) -> Node: | |
| if self.at("op", "-"): | |
| self.take() | |
| return ("neg", self.unary()) | |
| return self.power() | |
| def power(self) -> Node: | |
| base = self.primary() | |
| if self.at("op", "^"): | |
| self.take() | |
| return ("pow", base, self.unary()) | |
| return base | |
| def primary(self) -> Node: | |
| kind, value = self.take() | |
| if kind == "num": | |
| return ("num", Fraction(value)) | |
| if kind == "id": | |
| return ("var", value) | |
| if (kind, value) == ("op", "("): | |
| inner = self.term() | |
| self.expect("op", ")") | |
| return inner | |
| raise ParseError("unexpected %r in a term" % (value or "end of input")) | |
| def parse_problem(text: str) -> Node: | |
| """Parse one sentence of the math language into an AST (formalizer A).""" | |
| text = check_input_text(text) | |
| try: | |
| return _Parser(tokenize(text)).problem() | |
| except RecursionError as exc: | |
| raise ParseError("expression nested too deeply") from exc | |