File size: 38,426 Bytes
d9b105f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 | #!/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"(?<![\w.])(%s)\s*[- ]?\s*(%s)(?![a-z])" % (NUM, UNIT_ALT), re.I)
RX_MONEY = re.compile(r"\$\s*(%s)" % NUM)
RX_RANGE = re.compile(r"\bfrom\s+(%s)\s*(%s)?\s+(?:up\s+)?to\s+(%s)\s*(%s)(?![a-z])" % (NUM, UNIT_ALT, NUM, UNIT_ALT), re.I)
RX_PRICE = re.compile(r"(?:\$\s*(%s)|(%s)\s*cents?)\s*(?:per|a|/)\s*(kwh|kilowatt-hour|wh)" % (NUM, NUM), re.I)
RX_TEMP = re.compile(r"(-?\d+(?:\.\d+)?)\s*(?:°\s*|degrees?\s+)?(c|f|celsius|fahrenheit)\b", re.I)
RX_PER_DAY = re.compile(r"(%s)\s*(hours?|minutes?|hrs?|mins?)\s+(?:a|per|each|every)\s+(day|week)" % NUM, re.I)
RX_EVERY_DAY = re.compile(r"(%s)\s*(hours?|minutes?|hrs?|mins?)\s+(?:every|each)\s+day" % NUM, re.I)
RX_DAYS_PER_WEEK = re.compile(r"(%s)\s*days?\s+(?:a|per|each)\s+week" % NUM, re.I)
RX_DAYS_SPAN = re.compile(r"(?:for\s+|a\s+|over\s+)?(%s)[- ]days?(?:\s+month)?" % NUM, re.I)
RX_YEAR = re.compile(r"\b(?:for|over)\s+a\s+year\b", re.I)
RX_RATIO = re.compile(r"\b(twice|double|triple|half|\d+(?:\.\d+)?\s*times)\s+(?:the\s+)?earth'?s\s+(mass|radius)", re.I)
RX_RATIO_UNITS = re.compile(r"\b(\d+(?:\.\d+)?)\s+earth\s+(mass|masses|radius|radii)\b", re.I)
RX_RATIO_ITS = re.compile(r"\b(twice|double|triple|half|\d+(?:\.\d+)?\s*times)\s+(?:the\s+|its\s+)(mass|radius)", re.I)
RX_EMIT = re.compile(r"(?:each|every|per)\s+kwh\s+(?:releases|emits|produces)\s+(%s)\s*(kg|g|grams?|kilograms?)" % NUM, re.I)
RX_EMIT2 = re.compile(r"(%s)\s*(kg|g)\s+(?:of\s+)?co2\s+per\s+kwh" % NUM, re.I)
RX_COEF = re.compile(r"(?:coefficient|expansion)[^.?]*?(%s)\s*(?:per|/)\s*(?:degree|°)\s*c" % NUM, re.I)
RX_SPECHEAT = re.compile(r"specific heat\s*(?:of\s*)?(%s)\s*j\s*/\s*kg" % NUM, re.I)
RX_ACROSS = re.compile(r"(%s)\s*(m|metres?|meters?|ft|feet)\s+(?:across|in diameter|wide)\b" % NUM, re.I)
RX_ROOM = re.compile(r"(%s)\s*(m|ft)?\s*(?:by|x)\s*(%s)\s*(m|ft)?\b(?:[^.?]*?(%s)\s*(m|ft)\s+(?:ceiling|high|tall))?" % (NUM, NUM, NUM), re.I)
RX_ACH = re.compile(r"(%s)\s*(?:air changes per hour|ach)\b" % NUM, re.I)
RX_TALL = re.compile(r"(%s)\s*(m|metres?|meters?|ft|feet|cm)\s+(?:tall|high|deep|long)\b" % NUM, re.I)
MATERIALS = r"water|ice|aluminium|aluminum|copper|iron|steel|glass|lead|gold|silver|concrete|oil|brass|granite"
RX_MATERIAL = re.compile(r"\bkg\s+of\s+(%s)\b" % MATERIALS, re.I)
RX_NIGHTS = re.compile(r"how many\s+(%s)[- ](hours?|minutes?)\s+(\w+)" % NUM, re.I)
TOWARD = re.compile(r"\b(?:toward|towards|approach\w*|coming (?:at|toward)|comes? toward)\b", re.I)
AWAY = re.compile(r"\b(?:away|reced\w*|leaving)\b", re.I)
def read_givens(text):
"""-> 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"(?<![A-Za-z^\d.,])\d+(?:[.,]\d+)*", t) if not all(used[m.start():m.end()])]
flags["unread_numbers"] = unread
return out, flags
# ---------------------------------------------------------------- reading the question: goal
GOALS = [
(r"\bis (?:that|it|this) (?:compliant|safe|okay|ok)\b.*\bcold[- ]holding\b|\bcold[- ]holding\b.*\bis (?:that|it)\b", ("bool", "cold_hold")),
(r"\bhow many\s+(?:kilowatt-hours|kwh)\b|\bin kwh\b|\bkilowatt-hours of\b", ("dim", ENERGY, "kWh", 3.6e6)),
(r"\bhow many\s+kilojoules\b|\bin kilojoules\b|\bin kj\b", ("dim", ENERGY, "kJ", 1000)),
(r"\bin horsepower\b|\bhow many horsepower\b", ("dim", POWER, "hp", 745.69987)),
(r"\bwhat (?:does|do|would|will)\b.*\bcost\b|\bcost (?:in dollars|how much)\b|\bhow much does .* cost\b", ("dim", MONEY, "$", 1)),
(r"\bwhat frequency\b|\bwhat pitch\b", ("dim", FREQ, "Hz", 1)),
(r"\bhow many seconds\b|\bhow long\b.*\bfall\b", ("dim", TIME, "s", 1)),
(r"\bacceleration\b", ("dim", ACC, "m/s²", 1)),
(r"\bhow much (?:does|would|will) .* weigh\b|\bwhat (?:does|would|will) .* weigh\b", ("dim", D(kg=1, m=1, s=-2), "N", 1)),
(r"\bhow many litres\b|\bhow many liters\b|\bin litres\b", ("dim", VOL, "L", 1e-3)),
(r"\bhow many (?:us )?gallons\b", ("dim", VOL, "US gallons", 3.785411784e-3)),
(r"\bhow many kilograms\b|\bhow many kg\b|\bin kilograms\b", ("dim", MASS, "kg", 1)),
(r"\bhow many millimetres\b|\bhow many millimeters\b|\bin mm\b", ("dim", LEN, "mm", 1e-3)),
(r"\bhow many cfm\b|\bcfm of airflow\b", ("dim", FLOW, "CFM", 0.3048 ** 3 / 60)),
]
RX_GOAL_UNIT = re.compile(r"\b(?:how many|in|into|as|to)\s+(?:us\s+)?(%s)(?![a-z])" % UNIT_ALT, re.I)
RX_COLD_BOOL = re.compile(r"\bcold[- ]holding\b", re.I)
RX_BOOL_ASK = re.compile(r"\b(?:is|are)\b[^?]*\b(?:compliant|safe|okay|ok|acceptable|allowed|within)\b|\b(?:compliant|safe|okay|acceptable)\b[^?]*\?", re.I)
RX_MONEY_ASK = re.compile(r"\b(?:cost|costs|bill|spend|pay)\b", re.I)
def read_goal(text):
t = str(text).lower()
q = [s for s in re.split(r"(?<=[.?!])\s+", t.strip()) if s]
ask = q[-1] if q else t
m = RX_NIGHTS.search(text)
if m:
return ("count", m.group(3).lower())
if RX_COLD_BOOL.search(t) and RX_BOOL_ASK.search(t):
return ("bool", "cold_hold")
# an explicit unit asked for: "how many kWh", "in horsepower", "into kWh", "in m/s^2", "how many hours"
m = RX_GOAL_UNIT.search(ask)
if m:
u = unit_lookup(m.group(1))
if u:
return ("dim", u[1], m.group(1), u[0])
for rx, g in GOALS:
if g[0] != "bool" and re.search(rx, ask):
return g
if RX_MONEY_ASK.search(ask) and re.search(r"\b(?:what|how much|what's)\b", ask):
return ("dim", MONEY, "$", 1)
return None
WORDNUM = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
"eleven": 11, "twelve": 12, "fifteen": 15, "twenty": 20, "thirty": 30}
RX_WORDNUM = re.compile(r"\b(%s)\b(?=\s+(?:hours?|hrs?|minutes?|mins?|days?|weeks?|years?|seconds?|nights?)\b)" % "|".join(WORDNUM), re.I)
def normalise(text):
"""number words before a unit of time become digits ("for two weeks" -> "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])
|