"""formula_lib - 6.0: Wikidata's defining formulas read into systems the maths organ can check (no language model). For each formula item (library_raw.json from mine_formulas.py): 1. SYMBOLS every symbol Wikidata maps (P7235 + P9758) becomes a named quantity; a symbol whose quantity is a physical constant with a cited value (P1181) becomes a constant. Longest symbol text is replaced first. 2. READ the rest of the LaTeX must be plain algebra: numbers, + - * /, \\frac, ^, \\sqrt, parentheses, \\pi, and sin/cos/tan/exp/ln/log. Anything else (vectors, sums, integrals, derivatives, unmapped letters) is refused, with the reason - never guessed. 3. UNITS each quantity's unit is built from its ISQ dimension (P4020), written in SI; the organ's dimension check then decides whether the formula holds together. One equation per system. Writes library.json: {"systems": [sysdef + provenance], "refused": {reason: count}, "quantity_units": {...}}.""" from __future__ import annotations import collections import json import re import sys DIMKEY = {"L": 0, "M": 1, "T": 2, "I": 3, "Θ": 4, "\\Theta": 4, "N": 5} SI_BASE = ("m", "kg", "s", "A", "K", "mol") NAMED = {(2, 1, -2, 0, 0, 0): "J", (2, 1, -3, 0, 0, 0): "W", (1, 1, -2, 0, 0, 0): "N", (-1, 1, -2, 0, 0, 0): "Pa", (2, 1, -3, -1, 0, 0): "V", (2, 1, -3, -2, 0, 0): "ohm", (0, 0, -1, 0, 0, 0): "Hz"} def _plain(c): """a mathematical alphanumeric (sans-serif L, bold Theta, ...) -> its plain letter; the minus sign -> '-'""" import unicodedata if c == "−": return "-" n = unicodedata.name(c, "") if n.startswith("MATHEMATICAL") and "THETA" in n: return "Θ" m = re.search(r"MATHEMATICAL .*CAPITAL ([A-Z])$", n) return m.group(1) if m else c def mathml_text(x): """MathML (as WDQS returns P4020) -> 'L^(2)MT^(-2)'; plain text passes through""" if " (2, 1, -2, 0, 0, 0); None if it cannot be read (or has luminous intensity)""" text = mathml_text(text) t = text.replace("\\mathsf", "").replace("\\mathrm", "").replace("{", " ").replace("}", " ").replace("\\,", " ").replace("\\cdot", " ") t = t.replace("\\Theta", "Θ").replace("−", "-") if re.fullmatch(r"\s*1\s*", t): return (0,) * 6 d = [0] * 6 for m in re.finditer(r"([LMTINΘJ])\s*(?:\^\s*\(?\s*(-?\s*\d+)\s*\)?)?", t): if m.group(1) == "J": return None d[DIMKEY[m.group(1)]] += int((m.group(2) or "1").replace(" ", "")) rest = re.sub(r"([LMTINΘJ])\s*(?:\^\s*\(?\s*(-?\s*\d+)\s*\)?)?", "", t) if rest.strip(): return None return tuple(d) def unit_text(d): if d in NAMED: return NAMED[d] if not any(d): return "1" num = ["%s^%d" % (u, e) if e != 1 else u for u, e in zip(SI_BASE, d) if e > 0] den = ["%s^%d" % (u, -e) if e != -1 else u for u, e in zip(SI_BASE, d) if e < 0] return ("*".join(num) or "1") + ("/" + "/".join(den) if den else "") FUNCS = {"\\sin": "sin", "\\cos": "cos", "\\tan": "tan", "\\exp": "exp", "\\ln": "log", "\\log": "log", "\\sqrt": "sqrt"} STRIP = ["\\left", "\\right", "\\,", "\\;", "\\!", "\\quad", "\\displaystyle", "\\mathrm", "\\mathit", "\\textstyle", "\\big", "\\Big"] def _norm(s): s = s.strip().strip("$") for x in ("\\displaystyle", "\\textstyle"): s = s.replace(x, "") s = re.sub(r"\\(?:mathrm|mathit|text|textrm|operatorname)\s*\{([^{}]*)\}", r"\1", s) for x in ("\\,", "\\;", "\\!", "\\quad", "\\left", "\\right"): s = s.replace(x, "") s = re.sub(r"_\{(\\?[A-Za-z0-9]+)\}", r"_\1", s) # x_{e} -> x_e, so symbol and formula spell it alike s = re.sub(r"\s+", "", s) return s def toks(s): return re.findall(r"\\[A-Za-z]+|\\.|§\d+|.", s) def _braced(s, i): """s[i] == '{' -> (content, index after the closing brace)""" depth = 0 for j in range(i, len(s)): if s[j] == "{": depth += 1 elif s[j] == "}": depth -= 1 if depth == 0: return s[i + 1:j], j + 1 raise ValueError("unbalanced braces") def _arg(s, i): if i < len(s) and s[i] == "{": return _braced(s, i) if i < len(s): m = re.match(r"\d+(?:\.\d+)?|[A-Za-z]", s[i:]) if m: return m.group(0), i + len(m.group(0)) raise ValueError("missing argument") def to_sympy(tex): """plain-algebra LaTeX (symbols already replaced by names like q0, q1) -> a SymPy-readable string; ValueError otherwise""" s = tex for x in STRIP: s = s.replace(x, "") s = s.replace("\\cdot", "*").replace("\\times", "*").replace("\\pi", "(pi)").replace("·", "*").replace("−", "-") s = s.replace("\\tfrac", "\\frac").replace("\\dfrac", "\\frac") out, i = [], 0 while i < len(s): c = s[i] if s.startswith("\\frac", i): a, i = _arg(s, i + 5) b, i = _arg(s, i) out.append("((%s)/(%s))" % (to_sympy(a), to_sympy(b))) continue if s.startswith("\\sqrt", i): j = i + 5 if j < len(s) and s[j] == "[": k = s.index("]", j) n = s[j + 1:k] a, i = _arg(s, k + 1) out.append("((%s)**(1/(%s)))" % (to_sympy(a), to_sympy(n))) else: a, i = _arg(s, j) out.append("sqrt(%s)" % to_sympy(a)) continue m = re.match(r"\\(sin|cos|tan|exp|ln|log)", s[i:]) if m: out.append(FUNCS["\\" + m.group(1)]) i += len(m.group(0)) if i < len(s) and s[i] not in "({": a, i = _arg(s, i) out.append("(%s)" % to_sympy(a)) continue if c == "^": a, i = _arg(s, i + 1) out.append("**(%s)" % to_sympy(a)) continue if c == "{": a, i = _braced(s, i) out.append("(%s)" % to_sympy(a)) continue if c in "()+-*/=": out.append(c) i += 1 continue m = re.match(r"\d+(?:\.\d+)?", s[i:]) if m: out.append(m.group(0)) i += len(m.group(0)) continue m = re.match(r"§(\d+)", s[i:]) if m: out.append("q" + m.group(1)) i += len(m.group(0)) continue if s.startswith("(pi)", i): out.append("pi") i += 4 continue raise ValueError("not plain algebra at %r" % s[i:i + 12]) # implicit products: q0q1, 2q0, )( , q0(, )q0, number( r = " ".join(out) r = re.sub(r"(q\d+|\)|\d|pi)\s+(?=(q\d+|\(|sqrt|sin|cos|tan|exp|log|pi))", r"\1*", r) return r def build(raw): Q = raw["quantities"] systems, refused, qunits = [], collections.Counter(), {} def qinfo(qid): x = Q.get(qid) if not x or len(x["dims"]) != 1: return None d = isq(x["dims"][0]) return None if d is None else (x["label"], d) for f in raw["formulas"]: if len(f["formulas"]) != 1: refused["several formulas"] += 1 continue tex = _norm(f["formulas"][0]) if tex.count("=") != 1: refused["not one plain equation"] += 1 continue syms = {} bad = False for sym, qids in f["symbols"].items(): if len(qids) != 1: bad = True break syms[_norm(sym)] = qids[0] if bad: refused["a symbol mapped to several quantities"] += 1 continue names, quantities, constants = {}, {}, {} work = toks(tex) for k, (sym, qid) in enumerate(sorted(syms.items(), key=lambda kv: -len(toks(kv[0])))): st = toks(sym) if not st: continue hit, j, nw = False, 0, [] while j < len(work): if work[j:j + len(st)] == st: nw.append("§%d" % k) j += len(st) hit = True else: nw.append(work[j]) j += 1 if not hit: continue work = nw info = qinfo(qid) if info is None: bad = True break label, d = info name = "q%d" % k x = Q[qid] if x["constant"] and x["value"]: constants[name] = [label, x["value"]["amount"], x["value"]["unit"], d] else: quantities[name] = "%s (%s)" % (label, unit_text(d)) names[name] = qid work = "".join(work) if bad: refused["a quantity without one readable dimension"] += 1 continue try: expr = to_sympy(work) except (ValueError, RecursionError) as e: refused["not plain algebra"] += 1 continue if len(quantities) < 2: refused["fewer than two quantities"] += 1 continue systems.append({"title": f["label"], "wikidata": f["id"], "latex": f["formulas"][0], "equations": [expr], "quantities": quantities, "constants_raw": constants, "qids": names}) for n, lb in quantities.items(): qunits[names[n]] = lb return {"systems": systems, "refused": dict(refused), "quantity_labels": qunits} if __name__ == "__main__": raw = json.load(open(sys.argv[1], encoding="utf-8")) out = build(raw) json.dump(out, open(sys.argv[2], "w", encoding="utf-8"), indent=1, ensure_ascii=False) print("systems", len(out["systems"]), "refused", out["refused"])