#!/usr/bin/env python3 """network_glue_v3 - glue v2 plus the class fixes from GLUE SEALED 1's verdict (GLUE_SEALED1_VERDICT.md). 0 hand adapters. 1. THE READER (shared with network_v2, which stays unchanged): glue v3 loads its OWN copy of the reader with standard units added - definitions, not fitted values: pascal/kPa, electronvolt, food Calorie (kcal), rpm, newton-metre, nanometre, km/s, kilonewton, GHz, MHz. Case-ambiguous prefixes in a lowercase table are left out (mW/MW, mPa/MPa): the reader would have to guess. network_v2 and glue v1/v2 in the same process keep the original reader. 2. SCALING FACES (geometry) follow the same final/intermediate rule as every face: a volume handed on to mass or cost needs its situation words, not its output name. The output name of an imperative dev question ("Calculate the area of ...", "Work out the volume of ...") is read like a wh-question's. 3. FINAL STEPS: a final step's own output name may be met by the goal's dimension, when the question names the face's situation through at least one of its distinctive words (IDF above the median of the face vocabulary) - "how many seconds until it lands" reaches the fall face through "dropped/falls", not through its word "long". 4. COVERAGE: a condition word blocks only when it belongs to a fillable face whose output is the goal's kind (a competing reading of this question), plus names - not to any face that could read the quantities. usage: network_glue_v3.py [question ...]""" from __future__ import annotations import collections import json import os import re import statistics import sys import types HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) EXTRA_UNITS = ''' _u("pa|pascal|pascals", 1, D(kg=1, m=-1, s=-2)) _u("kpa|kilopascal|kilopascals", 1e3, D(kg=1, m=-1, s=-2)) _u("ev|electronvolt|electronvolts|electron volt|electron volts", 1.602176634e-19, ENERGY) _u("kcal|kilocalorie|kilocalories|food calorie|food calories", 4184, ENERGY) # rpm left out: as torque x rpm it hides 2*pi (rev -> rad); dimensional analysis cannot see it (the 09-30 law) _u("n·m|n m|n-m|newton-metre|newton-metres|newton metre|newton metres", 1, ENERGY) _u("nm|nanometre|nanometres|nanometer|nanometers", 1e-9, LEN) _u("km/s", 1000, VEL) _u("kn|kilonewton|kilonewtons", 1e3, D(kg=1, m=1, s=-2)) _u("ghz|gigahertz", 1e9, FREQ) _u("mhz|megahertz", 1e6, FREQ) # compound units "a per b" composed from units already defined (a density must never be read as a mass): every # numerator unit over the common denominators of volume, area, time, mass and length for _num in [k for k in list(UNITS) if " " not in k and "/" not in k and len(k) > 1]: for _den in ("cubic metre", "cubic metres", "m3", "litre", "litres", "liter", "liters", "square metre", "square metres", "m2", "second", "hour", "kg", "kilogram", "metre", "meter"): _f1, _d1 = UNITS[_num] _f2, _d2 = UNITS[_den] _key = _num + " per " + _den if _key not in UNITS and not isinstance(_d1, str): UNITS[_key] = (_f1 / _f2, dmul(_d1, _d2, -1)) ''' def _load(name, path, subs): src = open(path, encoding="utf-8").read() for a, b in subs: assert a in src, (name, a[:40]) src = src.replace(a, b, 1) if a == "NUMW = {" else src.replace(a, b) mod = types.ModuleType(name) mod.__file__ = path sys.modules[name] = mod exec(compile(src, path, "exec"), mod.__dict__) return mod reader = _load("reader_v3", os.path.join(HERE, "network_v2.py"), [("NUMW = {", EXTRA_UNITS + "\nNUMW = {")]) g1 = _load("glue1_v3", os.path.join(HERE, "network_glue_v1.py"), [("from network_v2 import", "from reader_v3 import")]) g2 = _load("glue2_v3", os.path.join(HERE, "network_glue_v2.py"), [("from network_v2 import", "from reader_v3 import"), ("from network_glue_v1 import", "from glue1_v3 import")]) stems, words, Face2 = g2.stems, g2.words, g2.Face2 WH = re.compile(r"\b(?:what|how|which|calculate|determine|find|give|compute|work out)\b(.*?)" r"(?:\bof\b|\bdoes\b|\bdo\b|\bat\b|\bwill\b|\bfor\b|\bwith\b|\?|\.|$)", re.I) class GlueNetwork3(g2.GlueNetwork2): def __init__(self, *a, **k): super().__init__(*a, **k) vals = sorted(self.idf.values()) self.idf_median = statistics.median(vals) if vals else 0.0 @staticmethod def _wh_words(template): last = [s for s in re.split(r"(?<=[.?!])\s+", template) if s][-1:] or [template] m = WH.search(last[0]) return words(m.group(1)) if m else set() def _distinct(self, f): return {w for w in stems(f.words - f.conditions) if self.idf.get(w, 0) > self.idf_median} def _final(self, f, goal_dim): if f.out_kind == "bool": return True if f.power is not None: d = reader.DIMLESS for _ in range(abs(f.power)): d = reader.dmul(d, reader.LEN, 1 if f.power > 0 else -1) return d == goal_dim return f.out_dim == goal_dim def solve(self, text): text = reader.normalise(text) givens, flags = reader.read_givens(text) goal = reader.read_goal(text) base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)} if goal is None: return dict(base, status="declined", reason="no goal I can reach") if not givens: return dict(base, status="declined", reason="no quantities to work from") for q in givens: bad = reader.valid_given(q) if bad: return dict(base, status="declined", reason=bad, check="validity") if flags.get("unread_numbers"): return dict(base, status="declined", reason="numbers I could not read", check="all numbers read") qw = stems(words(text)) in_givens = " ".join(q.text for q in givens).lower() names = {g2._stem(w.lower()) for w in re.findall(r"(?<=[^.?!:]\s)([A-Z][a-z]+)\b", text) if not reader.unit_lookup(w) and w.lower() not in in_givens} goal_dim = goal[1] if goal[0] == "dim" else None def ok(f): ctx = getattr(f, "ctx", set()) if not ctx <= qw: return False if self._final(f, goal_dim): if stems(f.conditions) <= qw: return bool(f.conditions) or self.fit(f, qw) >= 0.5 or bool(self._distinct(f) & qw) # its output name is met by the goal's kind; its situation must still be named distinctively return bool(self._distinct(f) & qw) or bool(ctx & qw) return bool(stems(f.words - f.conditions) & qw or ctx & qw) eligible = [f for f in self.faces if ok(f)] sib = collections.defaultdict(list) for f in self.faces: sib[(f.sid, f.signature(), f.out_kind)].append(f) keep = [] for f in eligible: group = sib[(f.sid, f.signature(), f.out_kind)] if len(group) == 1: keep.append(f) continue def score(x): others = set().union(*(stems(y.words) for y in group if y is not x)) return len((stems(x.words) - others) & qw) mine, rival = score(f), max(score(y) for y in group if y is not f) if mine >= 1 and mine > rival: keep.append(f) eligible = keep competing = [f for f in self.faces if self._final(f, goal_dim) and all(self._fillers(list(givens), set(), s) for s in f.slots)] all_conds = set().union(*(getattr(f, "ctx", set()) for f in competing)) if competing else set() eligible = [f for f in eligible if (f.out_kind == "bool") == (goal[0] == "bool")] eligible.sort(key=lambda f: -self.fit(f, qw)) frontier = [(list(givens), set(), [], 0, [])] for _depth in range(3): nxt = [] for pool, used, trace, hops, path in frontier: done = self._finish2(base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds) if done: return done if hops < 2: for f in eligible: for p2, u2, t2 in self._apply(f, pool, used, trace): nxt.append((p2, u2, t2, hops + 1, path + [f])) frontier = nxt[:200] return dict(base, status="declined", reason="no checked path from the givens to what is asked", eligible=[f.sid + ":" + f.kind for f in eligible[:6]]) def _covered(self, path, qw, names, all_conds): cover = set() for f in path: cover |= stems(f.words) | stems(f.conditions) return sorted(((qw & all_conds) | names) - cover) if __name__ == "__main__": net = GlueNetwork3(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3]) print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"})) for q in sys.argv[4:]: print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1200])