Download lgphys/parse_a.py from tailot/lingologos-physics: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/tailot/lingologos-physics/resolve/main/lgphys/parse_a.py
- Command line
-
hf download hf://datasets/tailot/lingologos-physics/lgphys/parse_a.py
-
curl -L -o parse_a.py https://huggingface.co/datasets/tailot/lingologos-physics/resolve/main/lgphys/parse_a.py
10.6 kB
| """Road A of the two readers: a hand written recursive descent over a token stream. | |
| The sentence of this dataset belongs to one of four kinds, and each kind has one shape: | |
| convert <number> <unit> to <unit> a unit change, for instance "convert 3 km to m" | |
| audit <term> = <term> dimensional homogeneity, "audit F*t = m*v" | |
| <target> from <quantity>, <quantity> Buckingham analysis, "period from mass, stiffness" | |
| potential node <k> circuit <n> resistors [<a> <b> <r>; ...] sources [<node> <amp>; ...] | |
| size <number> frequency <number> one node potential of a resistive network | |
| Two spelling conventions keep the language unambiguous: a unit that carries a dot is written glued | |
| together ("kg.m"), while a product or a quotient inside a term is written with explicit spaced | |
| operators ("m * v", "m / s"). A number of the question is an integer or a decimal ("0.1"); a ratio | |
| such as "25/18" appears only in the answers the pipeline computes, never in a sentence. There is no | |
| sign in front of a literal, because the questions of this dataset never ask for one. | |
| Anything that does not match one of the four shapes raises ParseError, and a reader that raises is | |
| not an error of the run: it is the honest statement that the sentence is outside the physical | |
| fragment. | |
| This road walks the tokens with a cursor and one function per grammar level. Road B in parse_b.py | |
| reads the same language by splitting the string at separators found outside brackets. The two roads | |
| share the token vocabulary and nothing else, so when they produce the same canonical text the | |
| sentence was really understood twice. | |
| """ | |
| from fractions import Fraction | |
| from typing import List, Optional, Tuple | |
| from .terms import literal | |
| from .tree import ParseError, parse_number | |
| from .units import SYMBOLS, parse_unit | |
| _OPERATORS = {"+": "add", "-": "sub", "*": "mul", "/": "div"} | |
| _LEVELS = (("+", "-"), ("*", "/")) | |
| _SPECIAL = "()[]=^;," | |
| _KEYWORDS = ("node", "circuit", "resistors", "sources", "size", "frequency", "from", "to") | |
| def _glued(text: str, index: int) -> bool: | |
| """Is this character part of a word? Only the dot is: it joins decimal digits and unit symbols. | |
| A slash is always an operator, so "kg.m" is one word while "m/s" reads as m divided by s. The | |
| unit slots of a conversion rejoin the pieces before handing them to the unit table. | |
| """ | |
| return text[index] == "." | |
| def _is_word_end(text: str, index: int) -> bool: | |
| char = text[index] | |
| if char.isspace() or char in _SPECIAL: | |
| return True | |
| return char in "*/+-" and not _glued(text, index) | |
| def _tokenize(text: str) -> List[str]: | |
| """Split a sentence into words, numbers, units and single character operators.""" | |
| tokens: List[str] = [] | |
| index = 0 | |
| while index < len(text): | |
| if text[index].isspace(): | |
| index += 1 | |
| continue | |
| if not _glued(text, index) and (text[index] in _SPECIAL or text[index] in "+-*/"): | |
| tokens.append(text[index]) | |
| index += 1 | |
| continue | |
| start = index | |
| while index < len(text) and not _is_word_end(text, index): | |
| index += 1 | |
| tokens.append(text[start:index]) | |
| return tokens | |
| def _number_of(token: str) -> Optional[Fraction]: | |
| """The token as an exact number, or None when it is a name.""" | |
| try: | |
| return parse_number(token) | |
| except ParseError: | |
| return None | |
| def _unit_of(token: str) -> Optional[str]: | |
| """The token as a unit expression, or None when it is not one.""" | |
| try: | |
| parse_unit(token) | |
| except (KeyError, ValueError): | |
| return None | |
| return token | |
| def _runs_on(token: Optional[str]) -> bool: | |
| """A unit expression runs until the keyword "to" or until the end of the sentence.""" | |
| return token is not None and token != "to" | |
| class _Cursor: | |
| """A position in the token list: the whole state of the recursive descent.""" | |
| def __init__(self, tokens: List[str]) -> None: | |
| self.tokens = tokens | |
| self.index = 0 | |
| def peek(self) -> Optional[str]: | |
| if self.index < len(self.tokens): | |
| return self.tokens[self.index] | |
| return None | |
| def take(self) -> str: | |
| token = self.peek() | |
| if token is None: | |
| raise ParseError("the sentence ends too early") | |
| self.index += 1 | |
| return token | |
| def expect(self, word: str) -> None: | |
| token = self.take() | |
| if token != word: | |
| raise ParseError("expected %s, found %s" % (word, token)) | |
| def number(self) -> Fraction: | |
| """A number of a slot: integer, decimal, or a compact ratio such as "1/10".""" | |
| value = _number_of(self.take()) | |
| if value is None: | |
| raise ParseError("expected a number in the sentence") | |
| while self.peek() == "/" and _number_of(self._ahead(1)) is not None: | |
| self.take() | |
| divisor = _number_of(self.take()) | |
| if divisor == 0: | |
| raise ParseError("a ratio may not divide by zero") | |
| value = value / divisor | |
| return value | |
| def _ahead(self, offset: int) -> Optional[str]: | |
| position = self.index + offset | |
| if position < len(self.tokens): | |
| return self.tokens[position] | |
| return None | |
| def unit(self) -> Tuple: | |
| """A unit expression: every token up to the next keyword, handed to the unit table.""" | |
| parts: List[str] = [] | |
| while _runs_on(self.peek()): | |
| parts.append(self.take()) | |
| if not parts: | |
| raise ParseError("a unit is needed") | |
| try: | |
| return parse_unit(" ".join(parts)) | |
| except (KeyError, ValueError): | |
| raise ParseError("not a unit: %s" % " ".join(parts)) | |
| def symbol(self) -> str: | |
| token = self.take() | |
| if token not in SYMBOLS: | |
| raise ParseError("unknown quantity %s" % token) | |
| return token | |
| def _atom(cursor: _Cursor) -> Tuple: | |
| token = cursor.take() | |
| if token == "(": | |
| node = _expression(cursor, 0) | |
| cursor.expect(")") | |
| return node | |
| if token in _SPECIAL or token in "+-*/": | |
| raise ParseError("unexpected %s inside a term" % token) | |
| value = _number_of(token) | |
| if value is not None: | |
| following = cursor.peek() | |
| if following is not None and following not in _SPECIAL and _number_of(following) is None \ | |
| and _unit_of(following) is not None: | |
| return literal(value, cursor.take()) | |
| return literal(value, "dimensionless") | |
| if token in _KEYWORDS: | |
| raise ParseError("%s is not a quantity" % token) | |
| if token not in SYMBOLS: | |
| raise ParseError("unknown quantity %s" % token) | |
| return ("sym", token) | |
| def _power(cursor: _Cursor) -> Tuple: | |
| node = _atom(cursor) | |
| while cursor.peek() == "^": | |
| cursor.take() | |
| token = cursor.take() | |
| if not token.isdigit(): | |
| raise ParseError("exponents are positive integers, found %s" % token) | |
| node = ("pow", node, int(token)) | |
| return node | |
| def _expression(cursor: _Cursor, level: int) -> Tuple: | |
| """One grammar level: additions bind loosest, powers bind tightest.""" | |
| if level >= len(_LEVELS): | |
| return _power(cursor) | |
| node = _expression(cursor, level + 1) | |
| while cursor.peek() in _LEVELS[level]: | |
| operator = _OPERATORS[cursor.take()] | |
| node = (operator, node, _expression(cursor, level + 1)) | |
| return node | |
| def _term(cursor: _Cursor) -> Tuple: | |
| node = _expression(cursor, 0) | |
| if cursor.peek() not in (None, "=", ")", ";"): | |
| raise ParseError("dangling %s inside a term" % cursor.peek()) | |
| return node | |
| def _convert(cursor: _Cursor) -> Tuple: | |
| cursor.expect("convert") | |
| value = cursor.number() | |
| start_unit = cursor.unit() | |
| cursor.expect("to") | |
| end_unit = cursor.unit() | |
| if cursor.peek() is not None: | |
| raise ParseError("dangling text after a conversion") | |
| return ("convert", value, start_unit, end_unit) | |
| def _audit(cursor: _Cursor) -> Tuple: | |
| if cursor.peek() == "audit": | |
| cursor.take() | |
| left = _term(cursor) | |
| cursor.expect("=") | |
| right = _term(cursor) | |
| if cursor.peek() is not None: | |
| raise ParseError("dangling text after an equation") | |
| return ("audit", left, right) | |
| def _analysis(cursor: _Cursor) -> Tuple: | |
| if cursor.peek() == "pi": | |
| cursor.take() | |
| target = cursor.symbol() | |
| cursor.expect("from") | |
| symbols = [cursor.symbol()] | |
| while cursor.peek() == ",": | |
| cursor.take() | |
| symbols.append(cursor.symbol()) | |
| if cursor.peek() is not None: | |
| raise ParseError("dangling text after a list of quantities") | |
| return ("pi", target, tuple(symbols)) | |
| def _rows(cursor: _Cursor, width: int) -> List[Tuple]: | |
| cursor.expect("[") | |
| rows: List[Tuple] = [] | |
| while cursor.peek() != "]": | |
| row = tuple(cursor.number() for _ in range(width)) | |
| rows.append(row) | |
| if cursor.peek() == ";": | |
| cursor.take() | |
| cursor.expect("]") | |
| if not rows: | |
| raise ParseError("at least one row is needed") | |
| return rows | |
| def _potential(cursor: _Cursor) -> Tuple: | |
| cursor.expect("potential") | |
| cursor.expect("node") | |
| asked = int(cursor.number()) | |
| cursor.expect("circuit") | |
| count = int(cursor.number()) | |
| cursor.expect("resistors") | |
| rows = _rows(cursor, 3) | |
| cursor.expect("sources") | |
| injections = _rows(cursor, 2) | |
| cursor.expect("size") | |
| size = cursor.number() | |
| cursor.expect("frequency") | |
| frequency = cursor.number() | |
| if cursor.peek() is not None: | |
| raise ParseError("dangling text after a network") | |
| resistors = tuple((int(a), int(b), resistance) for a, b, resistance in rows) | |
| sources = tuple((int(node), current) for node, current in injections) | |
| for node in (asked, count): | |
| if node < 0: | |
| raise ParseError("node numbers are not negative") | |
| return ("potential", asked, count, resistors, sources, size, frequency) | |
| def parse(sentence: str) -> Tuple: | |
| """Road A reading: the sentence as a syntax tree, or ParseError outside the fragment.""" | |
| text = (sentence or "").strip() | |
| if not text: | |
| raise ParseError("empty sentence") | |
| tokens = _tokenize(text) | |
| cursor = _Cursor(tokens) | |
| head = tokens[0] | |
| if head == "convert": | |
| return _convert(cursor) | |
| if head == "potential": | |
| return _potential(cursor) | |
| if head == "audit" or "=" in tokens: | |
| return _audit(cursor) | |
| if "from" in tokens: | |
| return _analysis(cursor) | |
| raise ParseError("outside the physical fragment: %s" % text) | |