#!/usr/bin/env python3 """network_v2 - v2 = v1.2 + BREADTH (phase 7a, 2026-09-30): more typed operations from existing nodes (geometry cylinder volume, thermo heating a named material / melting ice, carboncapture gasoline CO2, planetary weight) and DERIVED inputs: an operation's input may be computed by CORE_MATH from 2-3 givens first (miles / mpg -> gallons -> CO2), so paths run core -> specialist -> core. The v1 description follows. network_v1 - the Oracle7 SPECIALIST NETWORK (phases 1-4 of the 2026-09-30 plan). NODES (one byte each): the standing specialists (IDs 0..N-1 in registry order) + CORE_MATH (0xFE, the frozen core's exact dimensional arithmetic) . A node is called through a TYPED ADAPTER: typed inputs are rendered into a phrasing the specialist already answers (taken from its own dev panel), its reply is parsed back into a typed, unit-checked value. The specialists stay frozen and gated; nothing inside a node changes. PLAN: read the question into typed GIVENS (numbers with units, rates such as "8 hours a day", ratios such as "twice Earth's mass", temperatures, directions) and a typed GOAL (the dimension/unit asked for, or a yes/no compliance); search paths = up to 2 domain-node applications followed by one CORE_MATH combination that uses EVERY remaining given exactly once (exponent +1/-1) to reach the goal dimension. Every hop is CHECKED: physical validity of inputs (durations > 0, at most 24 hours in a day, non-negative magnitudes, ...), the node's reply parses to the expected unit, the final dimension matches the goal. No checked path -> the network declines (never guesses). PATH MEMORY (phase 4): a path that ran clean is stored under its question SHAPE (goal signature + given signatures) as a byte string; the next question of the same shape tries that path first. """ from __future__ import annotations import itertools import json import math import os import re import sys from fractions import Fraction HERE = os.path.dirname(os.path.abspath(__file__)) # ---------------------------------------------------------------- dimensions & units (SI base: m kg s A K $) BASE = ("m", "kg", "s", "A", "K", "$") def D(**e): return tuple(e.get(b, 0) for b in BASE) def dmul(a, b, k=1): return tuple(x + k * y for x, y in zip(a, b)) DIMLESS = D() LEN, MASS, TIME, AREA, VOL = D(m=1), D(kg=1), D(s=1), D(m=2), D(m=3) VEL, ACC, FREQ = D(m=1, s=-1), D(m=1, s=-2), D(s=-1) ENERGY, POWER = D(kg=1, m=2, s=-2), D(kg=1, m=2, s=-3) VOLT, CURR, CHARGE, MONEY = D(kg=1, m=2, s=-3, A=-1), D(A=1), D(A=1, s=1), D(**{"$": 1}) TEMP, INV_TEMP, FLOW = D(K=1), D(K=-1), D(m=3, s=-1) # name -> (factor to SI, dimension) UNITS = {} def _u(names, factor, dim): for n in names.split("|"): UNITS[n] = (factor, dim) _u("w|watt|watts", 1, POWER) _u("kw|kilowatt|kilowatts", 1000, POWER) _u("hp|horsepower", 745.69987, POWER) _u("v|volt|volts", 1, VOLT) _u("a|amp|amps|ampere|amperes", 1, CURR) _u("ah|amp-hour|amp-hours", 3600, CHARGE) _u("s|sec|secs|second|seconds", 1, TIME) _u("min|mins|minute|minutes", 60, TIME) _u("h|hr|hrs|hour|hours", 3600, TIME) _u("day|days", 86400, TIME) _u("week|weeks", 7 * 86400, TIME) _u("year|years", 365 * 86400, TIME) _u("kwh|kilowatt-hour|kilowatt-hours", 3.6e6, ENERGY) _u("wh|watt-hour|watt-hours", 3600, ENERGY) _u("j|joule|joules", 1, ENERGY) _u("kj|kilojoule|kilojoules", 1000, ENERGY) _u("mph", 0.44704, VEL) _u("m/s", 1, VEL) _u("km/h|kph", 1 / 3.6, VEL) _u("m/s^2|m/s2|m/s²|metres per second squared|meters per second squared", 1, ACC) _u("m|metre|metres|meter|meters", 1, LEN) _u("km|kilometre|kilometres|kilometer|kilometers", 1000, LEN) _u("cm|centimetre|centimetres|centimeter|centimeters", 0.01, LEN) _u("mm|millimetre|millimetres|millimeter|millimeters", 0.001, LEN) _u("in|inch|inches", 0.0254, LEN) _u("ft|foot|feet", 0.3048, LEN) _u("mile|miles", 1609.344, LEN) _u("m2|m^2|m²|square metre|square metres|square meter|square meters", 1, AREA) _u("sq ft|square foot|square feet|ft2", 0.09290304, AREA) _u("m3|m^3|m³|cubic metre|cubic metres", 1, VOL) _u("l|litre|litres|liter|liters", 1e-3, VOL) _u("ml|millilitre|millilitres|milliliter|milliliters", 1e-6, VOL) _u("gallon|gallons|us gallon|us gallons|gal", 3.785411784e-3, VOL) _u("cfm", 0.3048 ** 3 / 60, FLOW) _u("kg|kilogram|kilograms", 1, MASS) _u("n|newton|newtons", 1, D(kg=1, m=1, s=-2)) _u("mpg|miles per gallon", 1609.344 / 3.785411784e-3, D(m=-2)) _u("g|gram|grams", 1e-3, MASS) _u("lb|lbs|pound|pounds", 0.45359237, MASS) _u("tonne|tonnes", 1000, MASS) _u("hz|hertz", 1, FREQ) _u("khz", 1e3, FREQ) _u("thz", 1e12, FREQ) _u("dollar|dollars", 1, MONEY) _u("cent|cents", 0.01, MONEY) NUMW = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "twice": 2, "double": 2, "triple": 3, "half": 0.5} class Q: """a typed quantity: SI value, dimension, the text it came from, a role hint, and whether it is a temperature point""" def __init__(self, v, dim, text="", role="", temp_point=False, src="given"): self.v, self.dim, self.text, self.role, self.temp_point, self.src = float(v), dim, text, role, temp_point, src def __repr__(self): return "Q(%.6g %s %s %s)" % (self.v, self.dim, self.role, self.text[:30]) def unit_lookup(u): u = u.lower().strip().rstrip(".") u = re.sub(r"\s+", " ", u) return UNITS.get(u) # ---------------------------------------------------------------- reading the question: givens NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*(?:x|×)\s*10\^?\s*-?\d+)?" def fnum(s): s = s.replace(",", "").replace("×", "x") m = re.match(r"(-?[\d.]+)\s*x\s*10\^?\s*(-?\d+)", s) return float(m.group(1)) * 10 ** int(m.group(2)) if m else float(s) UNIT_ALT = "|".join(sorted((re.escape(k) for k in UNITS), key=len, reverse=True)) RX_QTY = re.compile(r"(? list of Q. Consumed spans are masked so one number is read once.""" t = str(text) used = [False] * len(t) out = [] def take(m, grp=0): a, b = m.span(grp) if any(used[a:b]): return False for i in range(a, b): used[i] = True return True # a CHANGE given as a range: "from 0 to 20 mph" -> 20 mph of change (|B - A|, unit of B); temperatures excluded for m in RX_RANGE.finditer(t): u = unit_lookup(m.group(4)) if not u or u[1] == TEMP or (m.group(2) and unit_lookup(m.group(2)) != u): continue if take(m): out.append(Q(abs(fnum(m.group(3)) - fnum(m.group(1))) * u[0], u[1], m.group(0), "delta")) for m in RX_PRICE.finditer(t): if take(m): v = fnum(m.group(1)) if m.group(1) else fnum(m.group(2)) / 100 per = UNITS[m.group(3).lower()][0] out.append(Q(v / per, dmul(MONEY, ENERGY, -1), m.group(0), "price")) for rx in (RX_EMIT, RX_EMIT2): for m in rx.finditer(t): if take(m): f = UNITS[m.group(2).lower().rstrip("s") if m.group(2).lower() not in UNITS else m.group(2).lower()][0] out.append(Q(fnum(m.group(1)) * f / 3.6e6, dmul(MASS, ENERGY, -1), m.group(0), "emission")) for m in RX_COEF.finditer(t): if take(m, 1): out.append(Q(fnum(m.group(1)), INV_TEMP, m.group(0), "coefficient")) for m in RX_SPECHEAT.finditer(t): if take(m, 1): out.append(Q(fnum(m.group(1)), D(m=2, s=-2, K=-1), m.group(0), "specific_heat")) for m in RX_PER_DAY.finditer(t): if take(m): dur = fnum(m.group(1)) * UNITS[m.group(2).lower()][0] span = UNITS[m.group(3).lower()][0] out.append(Q(dur / span, DIMLESS, m.group(0), "duty")) for m in RX_DAYS_PER_WEEK.finditer(t): if take(m): out.append(Q(fnum(m.group(1)) / 7, DIMLESS, m.group(0), "duty")) for m in RX_RATIO.finditer(t): if take(m): w = m.group(1).lower() v = NUMW.get(w, None) or fnum(w.split()[0]) out.append(Q(v, DIMLESS, m.group(0), "earth_" + m.group(2).lower())) for m in RX_RATIO_UNITS.finditer(t): if take(m): kind = "mass" if m.group(2).lower().startswith("mass") else "radius" out.append(Q(fnum(m.group(1)), DIMLESS, m.group(0), "earth_" + kind)) for m in RX_RATIO_ITS.finditer(t): if take(m): w = m.group(1).lower() v = NUMW.get(w, None) or fnum(w.split()[0]) out.append(Q(v, DIMLESS, m.group(0), "earth_" + m.group(2).lower())) for m in RX_ACH.finditer(t): if take(m): out.append(Q(fnum(m.group(1)) / 3600, FREQ, m.group(0), "ach")) for m in RX_TALL.finditer(t): if take(m): f = unit_lookup(m.group(2))[0] out.append(Q(fnum(m.group(1)) * f, LEN, m.group(0), "height")) for m in RX_ACROSS.finditer(t): if take(m): f = unit_lookup(m.group(2))[0] out.append(Q(fnum(m.group(1)) * f, LEN, m.group(0), "diameter")) for m in RX_NIGHTS.finditer(t): if take(m, 1) and take(m, 2): out.append(Q(fnum(m.group(1)) * UNITS[m.group(2).lower()][0], TIME, m.group(0), "per_unit_" + m.group(3).lower())) for m in RX_YEAR.finditer(t): if take(m): out.append(Q(365 * 86400, TIME, m.group(0), "span")) temps = [] for m in RX_TEMP.finditer(t): a, b = m.span() if any(used[a:b]): continue u = m.group(2).lower()[0] v = fnum(m.group(1)) k = (v + 273.15) if u == "c" else ((v - 32) * 5 / 9 + 273.15) for i in range(a, b): used[i] = True temps.append(Q(k, TEMP, m.group(0), "temp", temp_point=True)) out.extend(temps) for m in RX_MONEY.finditer(t): if take(m): out.append(Q(fnum(m.group(1)), MONEY, m.group(0), "money")) for m in RX_QTY.finditer(t): a, b = m.span() if any(used[a:b]): continue u = unit_lookup(m.group(2)) if not u: continue for i in range(a, b): used[i] = True out.append(Q(fnum(m.group(1)) * u[0], u[1], m.group(0), "")) for m in RX_DAYS_SPAN.finditer(t): a, b = m.span(1) if any(used[a:b]): continue for i in range(m.start(), m.end()): used[i] = True out.append(Q(fnum(m.group(1)) * 86400, TIME, m.group(0), "span")) # direction of motion (a flag, not a number) flags = {"toward": bool(TOWARD.search(t)), "away": bool(AWAY.search(t))} mm = RX_MATERIAL.search(t) flags["material"] = mm.group(1).lower().replace("aluminum", "aluminium") if mm else "" flags["gasoline"] = bool(re.search(r"\b(?:gasoline|petrol|gas)\b|\bmpg\b|miles per gallon", t, re.I)) flags["melt"] = bool(re.search(r"\bmelt\w*\b", t, re.I)) and bool(re.search(r"\bice\b", t, re.I)) # v1.1: every number in the question must have been read into a given. A digit left over (a percentage, a count # the reader has no unit for) means the network did not understand the question - it must not answer it. # digits glued to a letter or caret belong to a unit or formula name ("m/s^2", "m2", "CO2", "MgSO4", "PM2.5"), not a quantity unread = [m.group(0) for m in re.finditer(r"(? "for 2 weeks")""" return RX_WORDNUM.sub(lambda m: str(WORDNUM[m.group(1).lower()]), str(text)) # ---------------------------------------------------------------- nodes class Registry: """byte IDs: specialists 0..N-1 in the standing order; CORE_MATH 0xFE""" CORE_MATH = 0xFE def __init__(self, standing, spec_root, combo_code): sys.path.insert(0, combo_code) from combo_runtime_v1 import _Organ # noqa: E402 self.ids = [] for s in standing: for m in s.split("+"): self.ids.append(m) self.byte = {sid: i for i, sid in enumerate(self.ids)} self._organ_cls, self.root, self._organs = _Organ, spec_root, {} def organ(self, sid): if sid not in self._organs: d = os.path.join(self.root, sid) self._organs[sid] = self._organ_cls(os.path.join(d, "manifest.json"), d) return self._organs[sid] def ask(self, sid, text): r = self.organ(sid).reply(text, "network") return r def g(v): """format a number for a node's phrasing""" return ("%.6g" % v) if abs(v) >= 1e-4 else ("%.4e" % v) RX_ANS = re.compile(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(?:×\s*10\^?(-?\d+))?", re.I) def parse_value(resp, unit_rx): """first number in the reply directly followed by the expected unit""" for m in re.finditer(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(%s)" % unit_rx, resp or "", re.I): try: return float(m.group(1).replace(",", "")) except ValueError: continue return None class Op: """a typed domain operation executed by a specialist node through its own proven phrasing""" def __init__(self, name, sid, slots, out_dim, render, out_unit_rx, out_factor, check=None, role_out=""): self.name, self.sid, self.slots, self.out_dim = name, sid, slots, out_dim self.render, self.out_unit_rx, self.out_factor, self.check, self.role_out = render, out_unit_rx, out_factor, check, role_out def _k_to_f(k): return (k - 273.15) * 9 / 5 + 32 def ops_for(reg): """the typed adapters. slots: list of (dim, role-predicate). render(args, flags) -> question text or None.""" has = reg.byte.__contains__ O = [] if has("acoustics"): O.append(Op("doppler", "acoustics", [(FREQ, lambda q: q.role == ""), (VEL, lambda q: True)], FREQ, lambda a, f: ("A siren of %s Hz is moving %s you at %s m/s. What frequency do you hear?" % (g(a[0].v), "toward" if f["toward"] and not f["away"] else "away from" if f["away"] and not f["toward"] else None, g(a[1].v))) if (f["toward"] != f["away"]) else None, r"Hz", 1)) phys = "physics-r3" if has("physics-r3") else "physics-r2" if has(phys): O.append(Op("kinetic_energy", phys, [(MASS, lambda q: True), (VEL, lambda q: True)], ENERGY, lambda a, f: "What is the kinetic energy of a %s kg ball moving at %s m/s?" % (g(a[0].v), g(a[1].v)), r"J\b|joules?", 1, role_out="kinetic")) O.append(Op("potential_energy", phys, [(MASS, lambda q: True), (LEN, lambda q: q.role == "")], ENERGY, lambda a, f: "What is the potential energy of a %s kg box lifted %s m?" % (g(a[0].v), g(a[1].v)), r"J\b|joules?", 1, role_out="potential")) if has("planetary"): def _grav(a, f): m = [q for q in a if q.role == "earth_mass"] r = [q for q in a if q.role == "earth_radius"] return ("What is the surface gravity on a planet with %s times Earth's mass and %s times Earth's radius?" % (g(m[0].v), g(r[0].v))) if m and r else None O.append(Op("surface_gravity", "planetary", [(DIMLESS, lambda q: q.role == "earth_mass"), (DIMLESS, lambda q: q.role == "earth_radius")], ACC, _grav, r"m/s²|m/s\^?2", 1, role_out="gravity")) if has("coldchain-v2"): O.append(Op("cold_hold", "coldchain-v2", [(TEMP, lambda q: q.temp_point)], "bool", lambda a, f: "Our walk-in cooler holds %s F. Is that okay for cold holding?" % g(round(_k_to_f(a[0].v), 1)), None, None)) if has("geometry-v4"): O.append(Op("circle_area", "geometry-v4", [(LEN, lambda q: q.role == "diameter")], AREA, lambda a, f: "Calculate the area of a circle of radius %s." % g(a[0].v / 2), r"", 1, role_out="area")) O.append(Op("cylinder_volume", "geometry-v4", [(LEN, lambda q: q.role == "diameter"), (LEN, lambda q: q.role == "height")], VOL, lambda a, f: "Determine the volume of a cylinder with radius %s and height %s." % (g(a[0].v / 2), g(a[1].v)), r"", 1, role_out="volume")) if has("thermo"): def _heat(a, f): if not f.get("material") or f["material"] == "ice" or a[2].v <= a[1].v: return None return "How much heat is needed to raise %s kg of %s from %s C to %s C?" % ( g(a[0].v), f["material"], g(round(a[1].v - 273.15, 4)), g(round(a[2].v - 273.15, 4))) O.append(Op("sensible_heat", "thermo", [(MASS, lambda q: True), (TEMP, lambda q: q.temp_point), (TEMP, lambda q: q.temp_point)], ENERGY, _heat, r"J\b", 1, role_out="heat")) O.append(Op("melt_ice", "thermo", [(MASS, lambda q: True)], ENERGY, lambda a, f: ("How much energy does it take to melt %s kg of ice?" % g(a[0].v)) if f.get("melt") else None, r"J\b", 1, role_out="heat")) if has("carboncapture"): O.append(Op("fuel_co2", "carboncapture", [(VOL, lambda q: True)], MASS, lambda a, f: ("How much CO2 is emitted by burning %s gallons of gasoline?" % g(a[0].v / 3.785411784e-3)) if f.get("gasoline") else None, r"kg\b", 1, role_out="co2")) if has("planetary"): O.append(Op("planet_weight", "planetary", [(MASS, lambda q: True), (DIMLESS, lambda q: q.role == "earth_mass"), (DIMLESS, lambda q: q.role == "earth_radius")], D(kg=1, m=1, s=-2), lambda a, f: "How much would an %s kg astronaut weigh on a planet with %s Earth masses and %s Earth radii?" % ( g(a[0].v), g(a[1].v), g(a[2].v)), r"N\b", 1, role_out="weight")) return O # ---------------------------------------------------------------- checks (generic physical validity - not item-specific) def valid_given(q): if q.role == "duty" and not (0 < q.v <= 1): return "a duty of %s is more than the whole day" % q.text if q.dim in (TIME, MASS, LEN, AREA, VOL, CURR, CHARGE, FREQ, FLOW) and q.v <= 0 and not q.temp_point: return "%s is not a physical amount" % q.text if q.dim == POWER and q.v <= 0: return "%s is not a physical power" % q.text if q.v <= 0 and q.dim not in (DIMLESS, TEMP, MONEY) and not q.temp_point and q.role != "delta": return "%s is not a physical amount" % q.text if q.role in ("earth_mass", "earth_radius") and q.v <= 0: return "%s is not a physical body" % q.text return None # ---------------------------------------------------------------- core math: exponents over the remaining quantities def core_math(qs, goal_dim): """find exponents e_i in {+1,-1} (every quantity used exactly once) with prod q_i^e_i of dimension goal_dim. Temperature points are first reduced to their difference (two points -> one delta). Returns (value, formula) or None.""" qs = list(qs) pts = [q for q in qs if q.temp_point] if len(pts) == 2: qs = [q for q in qs if not q.temp_point] + [Q(abs(pts[1].v - pts[0].v), TEMP, "Δ(%s→%s)" % (pts[0].text, pts[1].text), "delta")] elif pts: return None n = len(qs) if n == 0 or n > 7: return None sols = [] for signs in itertools.product((1, -1), repeat=n): dim = DIMLESS for q, e in zip(qs, signs): dim = dmul(dim, q.dim, e) if dim == goal_dim: sols.append(signs) if not sols: return None # prefer the solution with the most +1 exponents (a product before a ratio); ambiguity with EQUAL counts -> decline best = max(sum(s) for s in sols) top = [s for s in sols if sum(s) == best] if len(top) > 1: vals = {round(math.prod(q.v ** e for q, e in zip(qs, s)), 9) for s in top} if len(vals) > 1: return None s = top[0] val = math.prod(q.v ** e for q, e in zip(qs, s)) formula = " × ".join(("%s" if e > 0 else "1/(%s)") % q.text for q, e in zip(qs, s)) return val, formula # ---------------------------------------------------------------- the network class Network: def __init__(self, standing, spec_root, combo_code, memory_path=None): self.reg = Registry(standing, spec_root, combo_code) self.ops = ops_for(self.reg) self.memory_path = memory_path self.memory = {} try: # v1.2: the HRR path memory (partial-cue recall) when numpy is available; JSON exact-shape memory always sys.path.insert(0, HERE) from path_hrr_v1 import PathHRR # noqa: E402 self.hrr = PathHRR() except Exception: # noqa: BLE001 self.hrr = None self.hrr_stats = {"exact": 0, "hrr_recalled": 0, "hrr_recalled_and_used": 0} if memory_path and os.path.exists(memory_path): try: self.memory = json.load(open(memory_path)) except (OSError, ValueError): self.memory = {} # a question SHAPE: what is asked + the kinds of givens (not their values) @staticmethod def shape(goal, givens, flags): gs = sorted("%s:%s" % (q.role or "-", q.dim) for q in givens) return json.dumps([str(goal[:2] if goal else None), gs, sorted(k for k, v in flags.items() if v)]) def _run_op(self, op, args, flags, trace): text = op.render(args, flags) if not text: return None r = self.reg.ask(op.sid, text) if not r or r.get("declined"): trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "declined": True, "reply": (r or {}).get("response")}) return "declined" if op.out_dim == "bool": v = r["response"].strip().lower() ans = True if re.match(r"^\W*yes\b", v) else False if re.match(r"^\W*no\b", v) else None trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "reply": r["response"]}) return ("bool", ans, r["response"]) if ans is not None else None val = parse_value(r["response"], op.out_unit_rx) if op.out_unit_rx else None if val is None and op.out_unit_rx == "": m = RX_ANS.search(r["response"]) val = float(m.group(1).replace(",", "")) if m else None trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "reply": r["response"], "value": val}) if val is None or not math.isfinite(val): return None return Q(val * op.out_factor, op.out_dim, "%s(%s)" % (op.name, ", ".join(a.text for a in args)), op.role_out, src=op.sid) @staticmethod def _spec_indices(spec): return set(spec[1]) if isinstance(spec, tuple) else {spec} def _slot_fillers(self, givens, dim, pred): """a slot is filled by ONE given of its dimension, or (v2) DERIVED by core math from TWO givens""" out = [i for i, q in enumerate(givens) if q.dim == dim and pred(q)] for i, j in itertools.combinations(range(len(givens)), 2): if givens[i].temp_point or givens[j].temp_point: continue cm = core_math([givens[i], givens[j]], dim) if cm and pred(Q(cm[0], dim, "derived", "")): out.append(("d", (i, j))) return out def _plans(self, givens, goal): """candidate plans: [] (core math only), then 1 op (slots from givens or derived pairs), then 2 ops (givens only). Each = list of (op, arg-specs); a spec is a given index or ("d", (i, j)) for a core-math-derived input.""" yield [] idx = range(len(givens)) for op in self.ops: fill = [self._slot_fillers(givens, d, pred) for d, pred in op.slots] temp_slots = [k for k, (d, _p) in enumerate(op.slots) if d == TEMP] for combo in itertools.product(*fill): # two temperatures keep the question's from -> to order (never swapped into a different process) if len(temp_slots) >= 2 and any(not isinstance(combo[a], int) or not isinstance(combo[b], int) or combo[a] > combo[b] for a, b in zip(temp_slots, temp_slots[1:])): continue seen = set() ok = True for sp in combo: ix = self._spec_indices(sp) if seen & ix: ok = False break seen |= ix if ok: yield [(op, combo)] for op1 in self.ops: for c1 in itertools.permutations(idx, len(op1.slots)): if not all(givens[i].dim == d and pred(givens[i]) for i, (d, pred) in zip(c1, op1.slots)): continue for op2 in self.ops: if op2 is op1: continue rest = [i for i in idx if i not in c1] for c2 in itertools.permutations(rest, len(op2.slots)): if all(givens[i].dim == d and pred(givens[i]) for i, (d, pred) in zip(c2, op2.slots)): yield [(op1, c1), (op2, c2)] def solve(self, text): text = normalise(text) givens, flags = read_givens(text) goal = 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 answerable goal in the question") if not givens: return dict(base, status="declined", reason="no quantities to work from") for q in givens: bad = 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: %s" % ", ".join(flags["unread_numbers"][:4]), check="all numbers read") flags = {k: v for k, v in flags.items() if k != "unread_numbers"} self._last_tokens = self._shape_tokens(goal, givens, flags) shape = self.shape(goal, givens, flags) remembered = self.memory.get(shape) plans = list(self._plans(givens, goal)) self._hrr_pref = None if remembered: self.hrr_stats["exact"] += 1 plans.sort(key=lambda p: [o.name for o, _ in p] != remembered["ops"]) elif self.hrr is not None: codes, res = self.hrr.recall(self._shape_tokens(goal, givens, flags)) if codes: names = [self.ops[c].name for c in codes if c < len(self.ops)] self.hrr_stats["hrr_recalled"] += 1 self._hrr_pref = names plans.sort(key=lambda p: [o.name for o, _ in p] != names) for plan in plans: trace, pool, used, ok = [], list(givens), set(), True final_bool = None for op, combo in plan: args = [] for sp, (d, _pred) in zip(combo, op.slots): if isinstance(sp, tuple): # v2: core math first, its result feeds the specialist cm = core_math([givens[i] for i in sp[1]], d) if not cm: ok = False break trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "derive", "formula": cm[1], "value": cm[0]}) args.append(Q(cm[0], d, "(%s)" % cm[1], "derived")) else: args.append(givens[sp]) if not ok: break res = self._run_op(op, args, flags, trace) if res is None or res == "declined": ok = False break for sp in combo: used |= self._spec_indices(sp) if isinstance(res, tuple) and res[0] == "bool": final_bool = res else: pool.append(res) if not ok: continue rest = [q for i, q in enumerate(givens) if i not in used] + pool[len(givens):] if goal[0] == "bool": if final_bool is None or rest: continue return self._done(base, shape, plan, trace, "yes" if final_bool[1] else "no", final_bool[2], goal, remembered) if goal[0] == "count": per = [q for q in rest if q.role.startswith("per_unit_")] if len(per) != 1: continue others = [q for q in rest if q is not per[0]] cm = core_math(others, TIME) if not cm: continue n = cm[0] / per[0].v trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "count", "formula": "(%s) / %s" % (cm[1], per[0].text), "value": n}) return self._done(base, shape, plan, trace, "%s" % g(n), "That is %s %s." % (g(round(n, 4)), goal[1]), goal, remembered) cm = core_math(rest, goal[1]) if not cm: continue val = cm[0] / goal[3] if not math.isfinite(val) or val < 0: continue if not plan and len(givens) == 1: # v1.1: a single given converted to another unit is not a multi-step problem - the core answers those return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only") if not plan and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens): # v1.1: the 'answer' is a given handed back unchanged - an echo, never an answer continue trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "dimensional", "formula": cm[1], "value": val, "unit": goal[2]}) unit = goal[2] say = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit) return self._done(base, shape, plan, trace, say, "The answer is %s." % say, goal, remembered) return dict(base, status="declined", reason="no checked path from the givens to what is asked") @staticmethod def _shape_tokens(goal, givens, flags): toks = ["goal:%s" % (goal[:2] if goal else None,)] toks += ["given:%s:%s" % (q.role or "-", q.dim) for q in givens] toks += ["flag:%s" % k for k, v in flags.items() if v and k != "unread_numbers"] return toks def _done(self, base, shape, plan, trace, answer, sentence, goal, remembered): path = [t["byte"] for t in trace] # every hop in order, core-math derivations included entry = {"ops": [o.name for o, _ in plan], "path": path, "hits": (remembered or {}).get("hits", 0) + 1} if getattr(self, "_hrr_pref", None) is not None and entry["ops"] == self._hrr_pref: self.hrr_stats["hrr_recalled_and_used"] += 1 if self.hrr is not None and not remembered: codes = [self.ops.index(o) for o, _ in plan] + ([0xFE] if goal[0] != "bool" else []) self.hrr.store(self._last_tokens, codes) self.memory[shape] = entry if self.memory_path: json.dump(self.memory, open(self.memory_path, "w"), indent=1) nodes = [t["node"] for t in trace] return dict(base, status="answered", answer=answer, response="%s (path: %s)" % (sentence, " → ".join(nodes)), path_bytes=bytes(path).hex(), trace=trace, reused_path=bool(remembered)) if __name__ == "__main__": net = Network(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3]) for q in sys.argv[4:]: print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1500])