diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/exam_log.jsonl b/root/organs10/physics/specialists/solved-pipe-radius-2/exam_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b4b8b4fbc9141252b89073abeaa78e7d3c1fbda --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/exam_log.jsonl @@ -0,0 +1 @@ +{"t": "2026-10-25T01:08:55Z", "heldout_sha": "08e6a3c13885e0e6b0c5362d53b6a56e64a146e13ae8a0894e84d062a65bcdc0", "files_sha": "47147f2d4e3d47f883b3356a0f25bdb51937dbb56b8a08c05d554cbe8454e871"} diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/manifest.json b/root/organs10/physics/specialists/solved-pipe-radius-2/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..dc2348c87907a723332806f2d894112cd748ff9d --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/manifest.json @@ -0,0 +1,41 @@ +{ + "id": "solved-pipe-radius-2", + "name": "Solved: pipe radius from Womersley number, angular frequency, kinematic viscosity (Womersley number (Wikidata Q2066584))", + "sources": [ + { + "name": "the maths organ: solved from the system q0 = q1*sqrt(((q2)/(q3))); checked by substitution into every equation and by a numeric solution at 12 points", + "licence": "yours" + } + ], + "organ": { + "module": "organ_formula_v3", + "class": "FormulaOrgan", + "init": {} + }, + "accept": { + "kinds": [ + "compute" + ], + "declines_in_domain": [ + "missing_input", + "out_of_domain" + ], + "context_regex": "\\bpipe\\ radius\\b" + }, + "panel": { + "path": "panel.json", + "scorer_module": "scorer_formula_v1", + "scorer_fn": "ok" + }, + "budgets": { + "latency_p50_ms": 200 + }, + "notes": "Solved by the maths organ from the system Womersley number (Wikidata Q2066584): 6 checked points used to write the panel's dev half, 6 its held-out half.", + "built_from": { + "questions": [ + "What is the pipe radius for Womersley number and angular frequency and kinematic viscosity?" + ], + "gap": "", + "node": "hod" + } +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/narrow_v1.py b/root/organs10/physics/specialists/solved-pipe-radius-2/narrow_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..647d4d5e961acd006c9de30f0ce8b0b8f5139cda --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/narrow_v1.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""narrow_v1 - the shared NARROWING rule for specialist organs (2026-09-29, from the full-core sweep): + + WORD PROBLEMS AND NARRATIVE TURNS BELONG TO THE HEAD. An organ answers a direct domain question. A turn that tells a + story ("Justine wants to put a deck ...", "A new energy drink advertises 106 calories for 8 ounces ...") or relates + quantities to each other ("the length is 9 inches more than the width") is a word problem, which the core's word- + problem organ owns; organs firing on its nouns declined it or answered a different question. + An organ may DECLINE only a short direct question (it is then refusing the domain question that was asked); on + anything longer it says nothing and the head answers. + +Narrowing only ever removes turns an organ takes, so on any input where it does not fire, the organ's reply is +byte-identical to the frozen version it wraps (checked per specialist by an invariance count before re-gating). +""" +import re + +RELATION = re.compile(r"\b(?:\d+(?:\.\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+){0,2}(?:more|less|fewer|longer|shorter)\s+than\b|" + r"\b(?:twice|three times|half)\s+(?:as\s+\w+\s+as\s+)?the\s+\w+\b", re.I) + + +# a RATE ("106 calories for 8 ounces", "3 apples per 2 dollars") makes the turn a proportion problem +RATE = re.compile(r"\b\d+(?:\.\d+)?\s+[a-z]+\s+(?:for|per|every)\s+(?:\d+(?:\.\d+)?|a|an|one|each)\s+[a-z]+", re.I) +NUM = re.compile(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pipe-radius-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/panel.json b/root/organs10/physics/specialists/solved-pipe-radius-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..30cd25e652e724bd560e573a1a837d9e338d42bf --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pipe radius for Womersley number 107.961, angular frequency 59.4105 and kinematic viscosity 5.77717?", + "a": "33.66598467638021", + "valid": true, + "kind": "compute", + "expect": 33.66598467638021, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [107.960666, 59.4105, 5.777165] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 107.961, angular frequency of 59.4105 and kinematic viscosity of 5.77717.", + "a": "33.66598467638021", + "valid": true, + "kind": "compute", + "expect": 33.66598467638021, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [107.960666, 59.4105, 5.777165] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 85.2416, angular frequency 160.878 and kinematic viscosity 2.69428?", + "a": "11.031234994512259", + "valid": true, + "kind": "compute", + "expect": 11.031234994512259, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [85.241623, 160.878442, 2.69428] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 85.2416, angular frequency of 160.878 and kinematic viscosity of 2.69428.", + "a": "11.031234994512259", + "valid": true, + "kind": "compute", + "expect": 11.031234994512259, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [85.241623, 160.878442, 2.69428] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 45.6157, angular frequency 4.97131 and kinematic viscosity 94.305?", + "a": "198.67636778664198", + "valid": true, + "kind": "compute", + "expect": 198.67636778664198, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [45.61567, 4.971307, 94.305046] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 45.6157, angular frequency of 4.97131 and kinematic viscosity of 94.305.", + "a": "198.67636778664198", + "valid": true, + "kind": "compute", + "expect": 198.67636778664198, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [45.61567, 4.971307, 94.305046] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 10.5638, angular frequency 198.839 and kinematic viscosity 0.671697?", + "a": "0.6139852812046626", + "valid": true, + "kind": "compute", + "expect": 0.6139852812046626, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [10.563843, 198.838955, 0.671697] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 10.5638, angular frequency of 198.839 and kinematic viscosity of 0.671697.", + "a": "0.6139852812046626", + "valid": true, + "kind": "compute", + "expect": 0.6139852812046626, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [10.563843, 198.838955, 0.671697] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 21.7931, angular frequency 29.5106 and kinematic viscosity 8.50341?", + "a": "11.698412852758777", + "valid": true, + "kind": "compute", + "expect": 11.698412852758777, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.793126, 29.510609, 8.503407] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 21.7931, angular frequency of 29.5106 and kinematic viscosity of 8.50341.", + "a": "11.698412852758777", + "valid": true, + "kind": "compute", + "expect": 11.698412852758777, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.793126, 29.510609, 8.503407] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 223.509, angular frequency 17.3414 and kinematic viscosity 7.10705?", + "a": "143.085874957845", + "valid": true, + "kind": "compute", + "expect": 143.085874957845, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [223.508796, 17.341435, 7.107049] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Tell me the pipe radius with Womersley number of 223.509, angular frequency of 17.3414 and kinematic viscosity of 7.10705.", + "a": "143.085874957845", + "valid": true, + "kind": "compute", + "expect": 143.085874957845, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [223.508796, 17.341435, 7.107049] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "What is the pipe radius for Womersley number 107.961 and angular frequency 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Tell me the pipe radius with Womersley number of 85.2416 and angular frequency of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "What is the pipe radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pipe radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pipe radius with Womersley number of -45.6157, angular frequency of 4.97131 and kinematic viscosity of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Womersley number: no example had one" + }, + { + "q": "Which pipe radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the Womersley number is 17.7888, angular frequency is 167.625 and the kinematic viscosity is 10.3291, what is the pipe radius?", + "a": "4.415776402295356", + "valid": true, + "kind": "compute", + "expect": 4.415776402295356, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [17.788778, 167.624948, 10.329054] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Could you work out the pipe radius given Womersley number = 17.7888, angular frequency = 167.625, kinematic viscosity = 10.3291?", + "a": "4.415776402295356", + "valid": true, + "kind": "compute", + "expect": 4.415776402295356, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [17.788778, 167.624948, 10.329054] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "I need the pipe radius for a Womersley number of 21.511, an angular frequency of 173.394 and a kinematic viscosity of 251.084, please.", + "a": "25.885341095712825", + "valid": true, + "kind": "compute", + "expect": 25.885341095712825, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.511016, 173.393638, 251.084037] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "If the Womersley number is 21.511, angular frequency is 173.394 and the kinematic viscosity is 251.084, what is the pipe radius?", + "a": "25.885341095712825", + "valid": true, + "kind": "compute", + "expect": 25.885341095712825, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.511016, 173.393638, 251.084037] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Could you work out the pipe radius given Womersley number = 129.245, angular frequency = 1.18359, kinematic viscosity = 15.9416?", + "a": "474.3284454009193", + "valid": true, + "kind": "compute", + "expect": 474.3284454009193, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [129.244984, 1.18359, 15.941612] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "I need the pipe radius for a Womersley number of 129.245, an angular frequency of 1.18359 and a kinematic viscosity of 15.9416, please.", + "a": "474.3284454009193", + "valid": true, + "kind": "compute", + "expect": 474.3284454009193, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [129.244984, 1.18359, 15.941612] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "If the Womersley number is 20.3966, angular frequency is 18.3169 and the kinematic viscosity is 6.8386, what is the pipe radius?", + "a": "12.462777083143786", + "valid": true, + "kind": "compute", + "expect": 12.462777083143786, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [20.396558, 18.316867, 6.838598] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Could you work out the pipe radius given Womersley number = 20.3966, angular frequency = 18.3169, kinematic viscosity = 6.8386?", + "a": "12.462777083143786", + "valid": true, + "kind": "compute", + "expect": 12.462777083143786, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [20.396558, 18.316867, 6.838598] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "I need the pipe radius for a Womersley number of 185.886, an angular frequency of 13.2373 and a kinematic viscosity of 4.71941, please.", + "a": "110.9919566133998", + "valid": true, + "kind": "compute", + "expect": 110.9919566133998, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [185.886273, 13.237311, 4.719415] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "If the Womersley number is 185.886, angular frequency is 13.2373 and the kinematic viscosity is 4.71941, what is the pipe radius?", + "a": "110.9919566133998", + "valid": true, + "kind": "compute", + "expect": 110.9919566133998, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [185.886273, 13.237311, 4.719415] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "Could you work out the pipe radius given Womersley number = 9.1061, angular frequency = 24.5721, kinematic viscosity = 108.451?", + "a": "19.130572143790193", + "valid": true, + "kind": "compute", + "expect": 19.130572143790193, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [9.106104, 24.572086, 108.450792] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "I need the pipe radius for a Womersley number of 9.1061, an angular frequency of 24.5721 and a kinematic viscosity of 108.451, please.", + "a": "19.130572143790193", + "valid": true, + "kind": "compute", + "expect": 19.130572143790193, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [9.106104, 24.572086, 108.450792] (the system Womersley number (Wikidata Q2066584))" + }, + { + "q": "If the Womersley number is 17.7888 and the angular frequency is 167.625, what is the pipe radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Could you work out the pipe radius given Womersley number = 21.511, angular frequency = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Do you know the pipe radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pipe radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pipe radius given Womersley number = -129.245, angular frequency = 1.18359, kinematic viscosity = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Womersley number: no example had one" + }, + { + "q": "What is a typical pipe radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/program.py b/root/organs10/physics/specialists/solved-pipe-radius-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1054a9f611764c2eb60e7ac0ad7c1d3cacb7a3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/program.py @@ -0,0 +1,7 @@ +"""pipe radius from Womersley number, angular frequency, kinematic viscosity (Womersley number (Wikidata Q2066584)) +The maths organ (systems.py): solved from the system q0 = q1*sqrt(((q2)/(q3))); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(womersley_number, angular_frequency, kinematic_viscosity): + return 1.0*angular_frequency**(-0.5)*kinematic_viscosity**0.5*womersley_number diff --git a/root/organs10/physics/specialists/solved-pipe-radius-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pipe-radius-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-plasma-pressure/organ_formula_v2.py b/root/organs10/physics/specialists/solved-plasma-pressure/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-plasma-pressure/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-plasma-pressure/panel.json b/root/organs10/physics/specialists/solved-plasma-pressure/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..072237b47d9189e52b25e5c0ebc95be0bb14462a --- /dev/null +++ b/root/organs10/physics/specialists/solved-plasma-pressure/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the plasma pressure for magnetic pressure 107.961 and magnetic pressure ratio 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [107.960666, 59.4105] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 107.961 and magnetic pressure ratio of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [107.960666, 59.4105] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 169.527 and magnetic pressure ratio 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [169.526958, 280.773702] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 169.527 and magnetic pressure ratio of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [169.526958, 280.773702] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 1.91195 and magnetic pressure ratio 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [1.911952, 82.240072] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 1.91195 and magnetic pressure ratio of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [1.911952, 82.240072] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 1.64379 and magnetic pressure ratio 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [1.643795, 252.709024] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 1.64379 and magnetic pressure ratio of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [1.643795, 252.709024] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 18.3169 and magnetic pressure ratio 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [18.316867, 6.838598] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 18.3169 and magnetic pressure ratio of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [18.316867, 6.838598] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 156.502 and magnetic pressure ratio 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [156.50181, 185.886273] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 156.502 and magnetic pressure ratio of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [156.50181, 185.886273] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "What is the plasma pressure for magnetic pressure 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic pressure ratio is not given" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic pressure ratio is not given" + }, + { + "q": "What is the plasma pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the plasma pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the plasma pressure with magnetic pressure of -1.91195 and magnetic pressure ratio of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic pressure: no example had one" + }, + { + "q": "Which plasma pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the magnetic pressure is 8.50728 and the magnetic pressure ratio is 17.7888, what is the plasma pressure?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [8.507283, 17.788778] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = 8.50728, magnetic pressure ratio = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [8.507283, 17.788778] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "I need the plasma pressure for a magnetic pressure of 8.24951 and a magnetic pressure ratio of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [8.24951, 0.634021] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "If the magnetic pressure is 8.24951 and the magnetic pressure ratio is 0.634021, what is the plasma pressure?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [8.24951, 0.634021] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = 0.318734, magnetic pressure ratio = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [0.318734, 9.566071] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "I need the plasma pressure for a magnetic pressure of 0.318734 and a magnetic pressure ratio of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [0.318734, 9.566071] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "If the magnetic pressure is 0.671697 and the magnetic pressure ratio is 14.2496, what is the plasma pressure?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [0.671697, 14.249569] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = 0.671697, magnetic pressure ratio = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [0.671697, 14.249569] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "I need the plasma pressure for a magnetic pressure of 21.7931 and a magnetic pressure ratio of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [21.793126, 29.510609] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "If the magnetic pressure is 21.7931 and the magnetic pressure ratio is 29.5106, what is the plasma pressure?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [21.793126, 29.510609] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = 153.15, magnetic pressure ratio = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [153.149965, 18.595315] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "I need the plasma pressure for a magnetic pressure of 153.15 and a magnetic pressure ratio of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "plasma pressure for [153.149965, 18.595315] (the system magnetic pressure ratio (Wikidata Q2098466))" + }, + { + "q": "If the magnetic pressure is 8.50728, what is the plasma pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic pressure ratio is not given" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic pressure ratio is not given" + }, + { + "q": "Do you know the plasma pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the plasma pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the plasma pressure given magnetic pressure = -0.318734, magnetic pressure ratio = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic pressure: no example had one" + }, + { + "q": "What is a typical plasma pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-plasma-pressure/program.py b/root/organs10/physics/specialists/solved-plasma-pressure/program.py new file mode 100644 index 0000000000000000000000000000000000000000..b02b07ac5b5ded2dda42c89a03a181587bd90164 --- /dev/null +++ b/root/organs10/physics/specialists/solved-plasma-pressure/program.py @@ -0,0 +1,7 @@ +"""plasma pressure from magnetic pressure, magnetic pressure ratio (magnetic pressure ratio (Wikidata Q2098466)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(magnetic_pressure, magnetic_pressure_ratio): + return 1.0*magnetic_pressure*magnetic_pressure_ratio diff --git a/root/organs10/physics/specialists/solved-plasma-pressure/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-plasma-pressure/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-plasma-pressure/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-poisson-s-ratio/organ_formula_v2.py b/root/organs10/physics/specialists/solved-poisson-s-ratio/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poisson-s-ratio/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-poisson-s-ratio/panel.json b/root/organs10/physics/specialists/solved-poisson-s-ratio/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ba47dcee13202440d60cba3734aed099fd9d79ec --- /dev/null +++ b/root/organs10/physics/specialists/solved-poisson-s-ratio/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Poisson's ratio for change in width 107.961 and change in length 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [107.960666, 59.4105] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 107.961 and change in length of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [107.960666, 59.4105] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 169.527 and change in length 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [169.526958, 280.773702] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 169.527 and change in length of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [169.526958, 280.773702] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 1.91195 and change in length 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [1.911952, 82.240072] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 1.91195 and change in length of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [1.911952, 82.240072] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 1.64379 and change in length 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [1.643795, 252.709024] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 1.64379 and change in length of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [1.643795, 252.709024] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 18.3169 and change in length 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [18.316867, 6.838598] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 18.3169 and change in length of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [18.316867, 6.838598] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 156.502 and change in length 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [156.50181, 185.886273] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 156.502 and change in length of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [156.50181, 185.886273] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "What is the Poisson's ratio for change in width 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in length is not given" + }, + { + "q": "Tell me the Poisson's ratio with change in width of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in length is not given" + }, + { + "q": "What is the Poisson's ratio of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Poisson's ratio of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Poisson's ratio with change in width of -1.91195 and change in length of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative change in width: no example had one" + }, + { + "q": "Which Poisson's ratio is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the change in width is 8.50728 and the change in length is 17.7888, what is the Poisson's ratio?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [8.507283, 17.788778] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = 8.50728, change in length = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [8.507283, 17.788778] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "I need the Poisson's ratio for a change in width of 8.24951 and a change in length of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [8.24951, 0.634021] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "If the change in width is 8.24951 and the change in length is 0.634021, what is the Poisson's ratio?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [8.24951, 0.634021] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = 0.318734, change in length = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [0.318734, 9.566071] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "I need the Poisson's ratio for a change in width of 0.318734 and a change in length of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [0.318734, 9.566071] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "If the change in width is 0.671697 and the change in length is 14.2496, what is the Poisson's ratio?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [0.671697, 14.249569] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = 0.671697, change in length = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [0.671697, 14.249569] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "I need the Poisson's ratio for a change in width of 21.7931 and a change in length of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [21.793126, 29.510609] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "If the change in width is 21.7931 and the change in length is 29.5106, what is the Poisson's ratio?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [21.793126, 29.510609] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = 153.15, change in length = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [153.149965, 18.595315] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "I need the Poisson's ratio for a change in width of 153.15 and a change in length of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "Poisson's ratio for [153.149965, 18.595315] (the system Poisson's ratio (Wikidata Q190453))" + }, + { + "q": "If the change in width is 8.50728, what is the Poisson's ratio?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in length is not given" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in length is not given" + }, + { + "q": "Do you know the Poisson's ratio of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Poisson's ratio of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Poisson's ratio given change in width = -0.318734, change in length = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative change in width: no example had one" + }, + { + "q": "What is a typical Poisson's ratio?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-poisson-s-ratio/program.py b/root/organs10/physics/specialists/solved-poisson-s-ratio/program.py new file mode 100644 index 0000000000000000000000000000000000000000..54ac6b780ed93bb8d3527c0df071e4419316f184 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poisson-s-ratio/program.py @@ -0,0 +1,7 @@ +"""Poisson's ratio from change in width, change in length (Poisson's ratio (Wikidata Q190453)) +The maths organ (systems.py): solved from the system q0 = q1 / q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(change_in_width, change_in_length): + return 1.0*change_in_width/change_in_length diff --git a/root/organs10/physics/specialists/solved-poisson-s-ratio/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-poisson-s-ratio/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poisson-s-ratio/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pomerantsev-number/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pomerantsev-number/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pomerantsev-number/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pomerantsev-number/panel.json b/root/organs10/physics/specialists/solved-pomerantsev-number/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7461bbaa7608810d47fbf494237b801b85fb6e02 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pomerantsev-number/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Pomerantsev number for volumic heat generation rate 107.961, characteristic length 59.4105, thermal conductivity 5.77717 and temperature difference 1.89126?", + "a": "34876.02488282469", + "valid": true, + "kind": "compute", + "expect": 34876.02488282469, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [107.960666, 59.4105, 5.777165, 1.891256] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 107.961, characteristic length of 59.4105, thermal conductivity of 5.77717 and temperature difference of 1.89126.", + "a": "34876.02488282469", + "valid": true, + "kind": "compute", + "expect": 34876.02488282469, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [107.960666, 59.4105, 5.777165, 1.891256] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 2.69428, characteristic length 48.921, thermal conductivity 157.223 and temperature difference 35.6412?", + "a": "1.150711723874745", + "valid": true, + "kind": "compute", + "expect": 1.150711723874745, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [2.69428, 48.920991, 157.22256, 35.641157] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 2.69428, characteristic length of 48.921, thermal conductivity of 157.223 and temperature difference of 35.6412.", + "a": "1.150711723874745", + "valid": true, + "kind": "compute", + "expect": 1.150711723874745, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [2.69428, 48.920991, 157.22256, 35.641157] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 0.318734, characteristic length 9.56607, thermal conductivity 126.709 and temperature difference 1.70503?", + "a": "0.13500650656818805", + "valid": true, + "kind": "compute", + "expect": 0.13500650656818805, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [0.318734, 9.566071, 126.709252, 1.705032] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 0.318734, characteristic length of 9.56607, thermal conductivity of 126.709 and temperature difference of 1.70503.", + "a": "0.13500650656818805", + "valid": true, + "kind": "compute", + "expect": 0.13500650656818805, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [0.318734, 9.566071, 126.709252, 1.705032] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 87.781, characteristic length 13.2084, thermal conductivity 246.329 and temperature difference 20.3966?", + "a": "3.0481035018869886", + "valid": true, + "kind": "compute", + "expect": 3.0481035018869886, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [87.781013, 13.208419, 246.329053, 20.396558] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 87.781, characteristic length of 13.2084, thermal conductivity of 246.329 and temperature difference of 20.3966.", + "a": "3.0481035018869886", + "valid": true, + "kind": "compute", + "expect": 3.0481035018869886, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [87.781013, 13.208419, 246.329053, 20.396558] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 156.502, characteristic length 185.886, thermal conductivity 13.2373 and temperature difference 4.71941?", + "a": "86561.75987783127", + "valid": true, + "kind": "compute", + "expect": 86561.75987783127, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [156.50181, 185.886273, 13.237311, 4.719415] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 156.502, characteristic length of 185.886, thermal conductivity of 13.2373 and temperature difference of 4.71941.", + "a": "86561.75987783127", + "valid": true, + "kind": "compute", + "expect": 86561.75987783127, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [156.50181, 185.886273, 13.237311, 4.719415] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 24.5721, characteristic length 108.451, thermal conductivity 1.69476 and temperature difference 49.4843?", + "a": "3446.1402376603787", + "valid": true, + "kind": "compute", + "expect": 3446.1402376603787, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [24.572086, 108.450792, 1.694755, 49.484326] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 24.5721, characteristic length of 108.451, thermal conductivity of 1.69476 and temperature difference of 49.4843.", + "a": "3446.1402376603787", + "valid": true, + "kind": "compute", + "expect": 3446.1402376603787, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [24.572086, 108.450792, 1.694755, 49.484326] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "What is the Pomerantsev number for volumic heat generation rate 107.961, characteristic length 59.4105 and thermal conductivity 5.77717?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature difference is not given" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of 2.69428, characteristic length of 48.921 and thermal conductivity of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature difference is not given" + }, + { + "q": "What is the Pomerantsev number of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Pomerantsev number of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Pomerantsev number with volumic heat generation rate of -0.318734, characteristic length of 9.56607, thermal conductivity of 126.709 and temperature difference of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volumic heat generation rate: no example had one" + }, + { + "q": "Which Pomerantsev number is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volumic heat generation rate is 167.625, characteristic length is 10.3291, thermal conductivity is 2.21571 and the temperature difference is 58.5346, what is the Pomerantsev number?", + "a": "137.8902772511644", + "valid": true, + "kind": "compute", + "expect": 137.8902772511644, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [167.624948, 10.329054, 2.215713, 58.534594] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = 167.625, characteristic length = 10.3291, thermal conductivity = 2.21571, temperature difference = 58.5346?", + "a": "137.8902772511644", + "valid": true, + "kind": "compute", + "expect": 137.8902772511644, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [167.624948, 10.329054, 2.215713, 58.534594] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "I need the Pomerantsev number for a volumic heat generation rate of 8.53158, a characteristic length of 124.718, a thermal conductivity of 1.91195 and a temperature difference of 82.2401, please.", + "a": "843.9728658653045", + "valid": true, + "kind": "compute", + "expect": 843.9728658653045, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [8.531577, 124.718185, 1.911952, 82.240072] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "If the volumic heat generation rate is 8.53158, characteristic length is 124.718, thermal conductivity is 1.91195 and the temperature difference is 82.2401, what is the Pomerantsev number?", + "a": "843.9728658653045", + "valid": true, + "kind": "compute", + "expect": 843.9728658653045, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [8.531577, 124.718185, 1.911952, 82.240072] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = 81.1967, characteristic length = 6.98086, thermal conductivity = 0.551236, temperature difference = 2.88512?", + "a": "2488.02400826893", + "valid": true, + "kind": "compute", + "expect": 2488.02400826893, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [81.196705, 6.980857, 0.551236, 2.88512] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "I need the Pomerantsev number for a volumic heat generation rate of 81.1967, a characteristic length of 6.98086, a thermal conductivity of 0.551236 and a temperature difference of 2.88512, please.", + "a": "2488.02400826893", + "valid": true, + "kind": "compute", + "expect": 2488.02400826893, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [81.196705, 6.980857, 0.551236, 2.88512] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "If the volumic heat generation rate is 1.16997, characteristic length is 1.14865, thermal conductivity is 21.7931 and the temperature difference is 29.5106, what is the Pomerantsev number?", + "a": "0.002400233255339044", + "valid": true, + "kind": "compute", + "expect": 0.002400233255339044, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [1.169968, 1.148652, 21.793126, 29.510609] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = 1.16997, characteristic length = 1.14865, thermal conductivity = 21.7931, temperature difference = 29.5106?", + "a": "0.002400233255339044", + "valid": true, + "kind": "compute", + "expect": 0.002400233255339044, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [1.169968, 1.148652, 21.793126, 29.510609] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "I need the Pomerantsev number for a volumic heat generation rate of 223.509, a characteristic length of 17.3414, a thermal conductivity of 7.10705 and a temperature difference of 30.2507, please.", + "a": "312.63617484684903", + "valid": true, + "kind": "compute", + "expect": 312.63617484684903, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [223.508796, 17.341435, 7.107049, 30.250749] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "If the volumic heat generation rate is 223.509, characteristic length is 17.3414, thermal conductivity is 7.10705 and the temperature difference is 30.2507, what is the Pomerantsev number?", + "a": "312.63617484684903", + "valid": true, + "kind": "compute", + "expect": 312.63617484684903, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [223.508796, 17.341435, 7.107049, 30.250749] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = 0.869111, characteristic length = 39.1753, thermal conductivity = 0.432217, temperature difference = 16.6571?", + "a": "185.26739451910058", + "valid": true, + "kind": "compute", + "expect": 185.26739451910058, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [0.869111, 39.175263, 0.432217, 16.657051] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "I need the Pomerantsev number for a volumic heat generation rate of 0.869111, a characteristic length of 39.1753, a thermal conductivity of 0.432217 and a temperature difference of 16.6571, please.", + "a": "185.26739451910058", + "valid": true, + "kind": "compute", + "expect": 185.26739451910058, + "dtype": "quantity", + "unit": "1", + "why": "Pomerantsev number for [0.869111, 39.175263, 0.432217, 16.657051] (the system Pomerantsev number (Wikidata Q104379986))" + }, + { + "q": "If the volumic heat generation rate is 167.625, characteristic length is 10.3291 and the thermal conductivity is 2.21571, what is the Pomerantsev number?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature difference is not given" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = 8.53158, characteristic length = 124.718, thermal conductivity = 1.91195?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature difference is not given" + }, + { + "q": "Do you know the Pomerantsev number of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Pomerantsev number of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Pomerantsev number given volumic heat generation rate = -81.1967, characteristic length = 6.98086, thermal conductivity = 0.551236, temperature difference = 2.88512?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volumic heat generation rate: no example had one" + }, + { + "q": "What is a typical Pomerantsev number?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pomerantsev-number/program.py b/root/organs10/physics/specialists/solved-pomerantsev-number/program.py new file mode 100644 index 0000000000000000000000000000000000000000..22a1818a73408e3c421daade6e3cb0c479dcf91f --- /dev/null +++ b/root/organs10/physics/specialists/solved-pomerantsev-number/program.py @@ -0,0 +1,7 @@ +"""Pomerantsev number from volumic heat generation rate, characteristic length, thermal conductivity, temperature difference (Pomerantsev number (Wikidata Q104379986)) +The maths organ (systems.py): solved from the system q1 = ((q0*q2 **(2))/(q3*q4)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volumic_heat_generation_rate, characteristic_length, thermal_conductivity, temperature_difference): + return 1.0*characteristic_length**2*volumic_heat_generation_rate/(temperature_difference*thermal_conductivity) diff --git a/root/organs10/physics/specialists/solved-pomerantsev-number/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pomerantsev-number/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pomerantsev-number/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-population-density/organ_formula_v2.py b/root/organs10/physics/specialists/solved-population-density/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-population-density/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-population-density/panel.json b/root/organs10/physics/specialists/solved-population-density/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..4881f81b0d01169fed240ee412600b910ffe8a9d --- /dev/null +++ b/root/organs10/physics/specialists/solved-population-density/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the population density for population 107.961 and area 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [107.960666, 59.4105] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 107.961 and area of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [107.960666, 59.4105] (the system Population density)" + }, + { + "q": "What is the population density for population 169.527 and area 280.774?", + "a": "0.6037850281809956", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809956, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [169.526958, 280.773702] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 169.527 and area of 280.774.", + "a": "0.6037850281809956", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809956, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [169.526958, 280.773702] (the system Population density)" + }, + { + "q": "What is the population density for population 1.91195 and area 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [1.911952, 82.240072] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 1.91195 and area of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [1.911952, 82.240072] (the system Population density)" + }, + { + "q": "What is the population density for population 1.64379 and area 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [1.643795, 252.709024] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 1.64379 and area of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [1.643795, 252.709024] (the system Population density)" + }, + { + "q": "What is the population density for population 18.3169 and area 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [18.316867, 6.838598] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 18.3169 and area of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [18.316867, 6.838598] (the system Population density)" + }, + { + "q": "What is the population density for population 156.502 and area 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [156.50181, 185.886273] (the system Population density)" + }, + { + "q": "Tell me the population density with population of 156.502 and area of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [156.50181, 185.886273] (the system Population density)" + }, + { + "q": "What is the population density for population 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the population density with population of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the population density of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the population density of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the population density with population of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative population: no example had one" + }, + { + "q": "Which population density is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the population is 8.50728 and the area is 17.7888, what is the population density?", + "a": "0.47823872966731146", + "valid": true, + "kind": "compute", + "expect": 0.47823872966731146, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [8.507283, 17.788778] (the system Population density)" + }, + { + "q": "Could you work out the population density given population = 8.50728, area = 17.7888?", + "a": "0.47823872966731146", + "valid": true, + "kind": "compute", + "expect": 0.47823872966731146, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [8.507283, 17.788778] (the system Population density)" + }, + { + "q": "I need the population density for a population of 8.24951 and an area of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [8.24951, 0.634021] (the system Population density)" + }, + { + "q": "If the population is 8.24951 and the area is 0.634021, what is the population density?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [8.24951, 0.634021] (the system Population density)" + }, + { + "q": "Could you work out the population density given population = 0.318734, area = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [0.318734, 9.566071] (the system Population density)" + }, + { + "q": "I need the population density for a population of 0.318734 and an area of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [0.318734, 9.566071] (the system Population density)" + }, + { + "q": "If the population is 0.671697 and the area is 14.2496, what is the population density?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [0.671697, 14.249569] (the system Population density)" + }, + { + "q": "Could you work out the population density given population = 0.671697, area = 14.2496?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [0.671697, 14.249569] (the system Population density)" + }, + { + "q": "I need the population density for a population of 21.7931 and an area of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [21.793126, 29.510609] (the system Population density)" + }, + { + "q": "If the population is 21.7931 and the area is 29.5106, what is the population density?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [21.793126, 29.510609] (the system Population density)" + }, + { + "q": "Could you work out the population density given population = 153.15, area = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [153.149965, 18.595315] (the system Population density)" + }, + { + "q": "I need the population density for a population of 153.15 and an area of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1/km^2", + "why": "population density for [153.149965, 18.595315] (the system Population density)" + }, + { + "q": "If the population is 8.50728, what is the population density?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the population density given population = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the population density of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the population density of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the population density given population = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative population: no example had one" + }, + { + "q": "What is a typical population density?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-population-density/program.py b/root/organs10/physics/specialists/solved-population-density/program.py new file mode 100644 index 0000000000000000000000000000000000000000..faf50b69c4bea821cbf4f0188d19ff8984adcddc --- /dev/null +++ b/root/organs10/physics/specialists/solved-population-density/program.py @@ -0,0 +1,7 @@ +"""population density from population, area (Population density) +The maths organ (systems.py): solved from the system D = N/A; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(population, area): + return 1.0*population/area diff --git a/root/organs10/physics/specialists/solved-population-density/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-population-density/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-population-density/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-population/organ_formula_v2.py b/root/organs10/physics/specialists/solved-population/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-population/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-population/panel.json b/root/organs10/physics/specialists/solved-population/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5c1c25bf65ff33d9a39993cabe845b14b51b9f38 --- /dev/null +++ b/root/organs10/physics/specialists/solved-population/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the population for population density 107.961 and area 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "population for [107.960666, 59.4105] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 107.961 and area of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "population for [107.960666, 59.4105] (the system Population density)" + }, + { + "q": "What is the population for population density 169.527 and area 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "population for [169.526958, 280.773702] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 169.527 and area of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "population for [169.526958, 280.773702] (the system Population density)" + }, + { + "q": "What is the population for population density 1.91195 and area 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "population for [1.911952, 82.240072] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 1.91195 and area of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "population for [1.911952, 82.240072] (the system Population density)" + }, + { + "q": "What is the population for population density 1.64379 and area 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "population for [1.643795, 252.709024] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 1.64379 and area of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "population for [1.643795, 252.709024] (the system Population density)" + }, + { + "q": "What is the population for population density 18.3169 and area 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "population for [18.316867, 6.838598] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 18.3169 and area of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "population for [18.316867, 6.838598] (the system Population density)" + }, + { + "q": "What is the population for population density 156.502 and area 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "population for [156.50181, 185.886273] (the system Population density)" + }, + { + "q": "Tell me the population with population density of 156.502 and area of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "population for [156.50181, 185.886273] (the system Population density)" + }, + { + "q": "What is the population for population density 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the population with population density of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the population of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the population of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the population with population density of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative population density: no example had one" + }, + { + "q": "Which population is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the population density is 8.50728 and the area is 17.7888, what is the population?", + "a": "151.3341636008708", + "valid": true, + "kind": "compute", + "expect": 151.3341636008708, + "dtype": "quantity", + "unit": "1", + "why": "population for [8.507283, 17.788778] (the system Population density)" + }, + { + "q": "Could you work out the population given population density = 8.50728, area = 17.7888?", + "a": "151.3341636008708", + "valid": true, + "kind": "compute", + "expect": 151.3341636008708, + "dtype": "quantity", + "unit": "1", + "why": "population for [8.507283, 17.788778] (the system Population density)" + }, + { + "q": "I need the population for a population density of 8.24951 and an area of 0.634021, please.", + "a": "5.230362271972723", + "valid": true, + "kind": "compute", + "expect": 5.230362271972723, + "dtype": "quantity", + "unit": "1", + "why": "population for [8.24951, 0.634021] (the system Population density)" + }, + { + "q": "If the population density is 8.24951 and the area is 0.634021, what is the population?", + "a": "5.230362271972723", + "valid": true, + "kind": "compute", + "expect": 5.230362271972723, + "dtype": "quantity", + "unit": "1", + "why": "population for [8.24951, 0.634021] (the system Population density)" + }, + { + "q": "Could you work out the population given population density = 0.318734, area = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "population for [0.318734, 9.566071] (the system Population density)" + }, + { + "q": "I need the population for a population density of 0.318734 and an area of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "population for [0.318734, 9.566071] (the system Population density)" + }, + { + "q": "If the population density is 0.671697 and the area is 14.2496, what is the population?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "population for [0.671697, 14.249569] (the system Population density)" + }, + { + "q": "Could you work out the population given population density = 0.671697, area = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "population for [0.671697, 14.249569] (the system Population density)" + }, + { + "q": "I need the population for a population density of 21.7931 and an area of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "population for [21.793126, 29.510609] (the system Population density)" + }, + { + "q": "If the population density is 21.7931 and the area is 29.5106, what is the population?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "population for [21.793126, 29.510609] (the system Population density)" + }, + { + "q": "Could you work out the population given population density = 153.15, area = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "population for [153.149965, 18.595315] (the system Population density)" + }, + { + "q": "I need the population for a population density of 153.15 and an area of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "population for [153.149965, 18.595315] (the system Population density)" + }, + { + "q": "If the population density is 8.50728, what is the population?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the population given population density = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the population of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the population of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the population given population density = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative population density: no example had one" + }, + { + "q": "What is a typical population?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-population/program.py b/root/organs10/physics/specialists/solved-population/program.py new file mode 100644 index 0000000000000000000000000000000000000000..eb0263b4f0629d5de4d3b87ac5f59faef46af2ff --- /dev/null +++ b/root/organs10/physics/specialists/solved-population/program.py @@ -0,0 +1,7 @@ +"""population from population density, area (Population density) +The maths organ (systems.py): solved from the system D = N/A; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(population_density, area): + return 1.0*area*population_density diff --git a/root/organs10/physics/specialists/solved-population/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-population/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-population/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/organ_formula_v2.py b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/panel.json b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e581e32eb555f2271b302ac34cd7463d90b9c9a4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 107.961, electric dipole moment 59.4105 and electric charge 5.77717?", + "a": "97.6769879688886", + "valid": true, + "kind": "compute", + "expect": 97.6769879688886, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [107.960666, 59.4105, 5.777165] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 107.961, electric dipole moment of 59.4105 and electric charge of 5.77717.", + "a": "97.6769879688886", + "valid": true, + "kind": "compute", + "expect": 97.6769879688886, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [107.960666, 59.4105, 5.777165] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 85.2416, electric dipole moment 160.878 and electric charge 2.69428?", + "a": "25.53051275584723", + "valid": true, + "kind": "compute", + "expect": 25.53051275584723, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [85.241623, 160.878442, 2.69428] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 85.2416, electric dipole moment of 160.878 and electric charge of 2.69428.", + "a": "25.53051275584723", + "valid": true, + "kind": "compute", + "expect": 25.53051275584723, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [85.241623, 160.878442, 2.69428] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 45.6157, electric dipole moment 4.97131 and electric charge 94.305?", + "a": "45.5629549328462", + "valid": true, + "kind": "compute", + "expect": 45.5629549328462, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [45.61567, 4.971307, 94.305046] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 45.6157, electric dipole moment of 4.97131 and electric charge of 94.305.", + "a": "45.5629549328462", + "valid": true, + "kind": "compute", + "expect": 45.5629549328462, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [45.61567, 4.971307, 94.305046] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 14.2496, electric dipole moment 41.6566 and electric charge 13.8779?", + "a": "11.247909331532885", + "valid": true, + "kind": "compute", + "expect": 11.247909331532885, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [14.249569, 41.656639, 13.877867] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 14.2496, electric dipole moment of 41.6566 and electric charge of 13.8779.", + "a": "11.247909331532885", + "valid": true, + "kind": "compute", + "expect": 11.247909331532885, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [14.249569, 41.656639, 13.877867] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 0.58813, electric dipole moment 59.2668 and electric charge 134.993?", + "a": "0.14909313609999306", + "valid": true, + "kind": "compute", + "expect": 0.14909313609999306, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [0.58813, 59.266839, 134.992958] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 0.58813, electric dipole moment of 59.2668 and electric charge of 134.993.", + "a": "0.14909313609999306", + "valid": true, + "kind": "compute", + "expect": 0.14909313609999306, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [0.58813, 59.266839, 134.992958] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 30.2507, electric dipole moment 308.158 and electric charge 178.166?", + "a": "28.521132582842963", + "valid": true, + "kind": "compute", + "expect": 28.521132582842963, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [30.250749, 308.158051, 178.165518] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 30.2507, electric dipole moment of 308.158 and electric charge of 178.166.", + "a": "28.521132582842963", + "valid": true, + "kind": "compute", + "expect": 28.521132582842963, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [30.250749, 308.158051, 178.165518] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the negatively charged particle for position of the positively charged particle 107.961 and electric dipole moment 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of 85.2416 and electric dipole moment of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "What is the position of the negatively charged particle of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the position of the negatively charged particle of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the position of the negatively charged particle with position of the positively charged particle of -45.6157, electric dipole moment of 4.97131 and electric charge of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position of the positively charged particle: no example had one" + }, + { + "q": "Which position of the negatively charged particle is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the position of the positively charged particle is 17.7888, electric dipole moment is 167.625 and the electric charge is 10.3291, what is the position of the negatively charged particle?", + "a": "1.5602890281928137", + "valid": true, + "kind": "compute", + "expect": 1.5602890281928137, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [17.788778, 167.624948, 10.329054] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = 17.7888, electric dipole moment = 167.625, electric charge = 10.3291?", + "a": "1.5602890281928137", + "valid": true, + "kind": "compute", + "expect": 1.5602890281928137, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [17.788778, 167.624948, 10.329054] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the negatively charged particle for a position of the positively charged particle of 21.511, an electric dipole moment of 173.394 and an electric charge of 251.084, please.", + "a": "20.82043575769134", + "valid": true, + "kind": "compute", + "expect": 20.82043575769134, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [21.511016, 173.393638, 251.084037] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the positively charged particle is 21.511, electric dipole moment is 173.394 and the electric charge is 251.084, what is the position of the negatively charged particle?", + "a": "20.82043575769134", + "valid": true, + "kind": "compute", + "expect": 20.82043575769134, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [21.511016, 173.393638, 251.084037] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = 129.245, electric dipole moment = 1.18359, electric charge = 15.9416?", + "a": "129.1707384498779", + "valid": true, + "kind": "compute", + "expect": 129.1707384498779, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [129.244984, 1.18359, 15.941612] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the negatively charged particle for a position of the positively charged particle of 129.245, an electric dipole moment of 1.18359 and an electric charge of 15.9416, please.", + "a": "129.1707384498779", + "valid": true, + "kind": "compute", + "expect": 129.1707384498779, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [129.244984, 1.18359, 15.941612] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the positively charged particle is 19.4474, electric dipole moment is 4.51548 and the electric charge is 16.8637, what is the position of the negatively charged particle?", + "a": "19.179594016177585", + "valid": true, + "kind": "compute", + "expect": 19.179594016177585, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [19.447357, 4.515475, 16.863707] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = 19.4474, electric dipole moment = 4.51548, electric charge = 16.8637?", + "a": "19.179594016177585", + "valid": true, + "kind": "compute", + "expect": 19.179594016177585, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [19.447357, 4.515475, 16.863707] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the negatively charged particle for a position of the positively charged particle of 41.2905, an electric dipole moment of 2.12277 and an electric charge of 86.0768, please.", + "a": "41.26584416509799", + "valid": true, + "kind": "compute", + "expect": 41.26584416509799, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [41.290505, 2.122767, 86.076802] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the positively charged particle is 41.2905, electric dipole moment is 2.12277 and the electric charge is 86.0768, what is the position of the negatively charged particle?", + "a": "41.26584416509799", + "valid": true, + "kind": "compute", + "expect": 41.26584416509799, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [41.290505, 2.122767, 86.076802] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = 88.6624, electric dipole moment = 0.633611, electric charge = 0.869111?", + "a": "87.93332766821878", + "valid": true, + "kind": "compute", + "expect": 87.93332766821878, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [88.662361, 0.633611, 0.869111] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the negatively charged particle for a position of the positively charged particle of 88.6624, an electric dipole moment of 0.633611 and an electric charge of 0.869111, please.", + "a": "87.93332766821878", + "valid": true, + "kind": "compute", + "expect": 87.93332766821878, + "dtype": "quantity", + "unit": "m", + "why": "position of the negatively charged particle for [88.662361, 0.633611, 0.869111] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the positively charged particle is 17.7888 and the electric dipole moment is 167.625, what is the position of the negatively charged particle?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = 21.511, electric dipole moment = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Do you know the position of the negatively charged particle of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the position of the negatively charged particle of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the position of the negatively charged particle given position of the positively charged particle = -129.245, electric dipole moment = 1.18359, electric charge = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position of the positively charged particle: no example had one" + }, + { + "q": "What is a typical position of the negatively charged particle?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/program.py b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/program.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd00a62c23c900fcb70f4b144f0d876756ac9c --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/program.py @@ -0,0 +1,7 @@ +"""position of the negatively charged particle from position of the positively charged particle, electric dipole moment, electric charge (electric dipole moment (Wikidata Q735135)) +The maths organ (systems.py): solved from the system q2 = q3*( q0 - q1 ); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(position_of_the_positively_charged_particle, electric_dipole_moment, electric_charge): + return 1.0*position_of_the_positively_charged_particle - 1.0*electric_dipole_moment/electric_charge diff --git a/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-negatively-ch/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-position-of-the-positively-ch/organ_formula_v2.py b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-position-of-the-positively-ch/panel.json b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..85e6e3680d22f1a6ee956534a477e3325cfd5629 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 107.961, electric dipole moment 59.4105 and electric charge 5.77717?", + "a": "118.24434381103545", + "valid": true, + "kind": "compute", + "expect": 118.24434381103545, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [107.960666, 59.4105, 5.777165] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 107.961, electric dipole moment of 59.4105 and electric charge of 5.77717.", + "a": "118.24434381103545", + "valid": true, + "kind": "compute", + "expect": 118.24434381103545, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [107.960666, 59.4105, 5.777165] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 85.2416, electric dipole moment 160.878 and electric charge 2.69428?", + "a": "144.9527324215615", + "valid": true, + "kind": "compute", + "expect": 144.9527324215615, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [85.241623, 160.878442, 2.69428] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 85.2416, electric dipole moment of 160.878 and electric charge of 2.69428.", + "a": "144.9527324215615", + "valid": true, + "kind": "compute", + "expect": 144.9527324215615, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [85.241623, 160.878442, 2.69428] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 45.6157, electric dipole moment 4.97131 and electric charge 94.305?", + "a": "45.66838529319577", + "valid": true, + "kind": "compute", + "expect": 45.66838529319577, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [45.61567, 4.971307, 94.305046] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 45.6157, electric dipole moment of 4.97131 and electric charge of 94.305.", + "a": "45.66838529319577", + "valid": true, + "kind": "compute", + "expect": 45.66838529319577, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [45.61567, 4.971307, 94.305046] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 10.5638, electric dipole moment 198.839 and electric charge 0.671697?", + "a": "306.58853267397757", + "valid": true, + "kind": "compute", + "expect": 306.58853267397757, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [10.563843, 198.838955, 0.671697] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 10.5638, electric dipole moment of 198.839 and electric charge of 0.671697.", + "a": "306.58853267397757", + "valid": true, + "kind": "compute", + "expect": 306.58853267397757, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [10.563843, 198.838955, 0.671697] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 21.7931, electric dipole moment 29.5106 and electric charge 8.50341?", + "a": "25.263571691223934", + "valid": true, + "kind": "compute", + "expect": 25.263571691223934, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [21.793126, 29.510609, 8.503407] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 21.7931, electric dipole moment of 29.5106 and electric charge of 8.50341.", + "a": "25.263571691223934", + "valid": true, + "kind": "compute", + "expect": 25.263571691223934, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [21.793126, 29.510609, 8.503407] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 223.509, electric dipole moment 17.3414 and electric charge 7.10705?", + "a": "225.9488293780626", + "valid": true, + "kind": "compute", + "expect": 225.9488293780626, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [223.508796, 17.341435, 7.107049] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 223.509, electric dipole moment of 17.3414 and electric charge of 7.10705.", + "a": "225.9488293780626", + "valid": true, + "kind": "compute", + "expect": 225.9488293780626, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [223.508796, 17.341435, 7.107049] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "What is the position of the positively charged particle for position of the negatively charged particle 107.961 and electric dipole moment 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of 85.2416 and electric dipole moment of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "What is the position of the positively charged particle of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the position of the positively charged particle of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the position of the positively charged particle with position of the negatively charged particle of -45.6157, electric dipole moment of 4.97131 and electric charge of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position of the negatively charged particle: no example had one" + }, + { + "q": "Which position of the positively charged particle is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the position of the negatively charged particle is 17.7888, electric dipole moment is 167.625 and the electric charge is 10.3291, what is the position of the positively charged particle?", + "a": "34.01726722685598", + "valid": true, + "kind": "compute", + "expect": 34.01726722685598, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [17.788778, 167.624948, 10.329054] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = 17.7888, electric dipole moment = 167.625, electric charge = 10.3291?", + "a": "34.01726722685598", + "valid": true, + "kind": "compute", + "expect": 34.01726722685598, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [17.788778, 167.624948, 10.329054] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the positively charged particle for a position of the negatively charged particle of 21.511, an electric dipole moment of 173.394 and an electric charge of 251.084, please.", + "a": "22.201595948121387", + "valid": true, + "kind": "compute", + "expect": 22.201595948121387, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [21.511016, 173.393638, 251.084037] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the negatively charged particle is 21.511, electric dipole moment is 173.394 and the electric charge is 251.084, what is the position of the positively charged particle?", + "a": "22.201595948121387", + "valid": true, + "kind": "compute", + "expect": 22.201595948121387, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [21.511016, 173.393638, 251.084037] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = 129.245, electric dipole moment = 1.18359, electric charge = 15.9416?", + "a": "129.31922907935774", + "valid": true, + "kind": "compute", + "expect": 129.31922907935774, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [129.244984, 1.18359, 15.941612] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the positively charged particle for a position of the negatively charged particle of 129.245, an electric dipole moment of 1.18359 and an electric charge of 15.9416, please.", + "a": "129.31922907935774", + "valid": true, + "kind": "compute", + "expect": 129.31922907935774, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [129.244984, 1.18359, 15.941612] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the negatively charged particle is 20.3966, electric dipole moment is 18.3169 and the electric charge is 6.8386, what is the position of the positively charged particle?", + "a": "23.07501147805773", + "valid": true, + "kind": "compute", + "expect": 23.07501147805773, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [20.396558, 18.316867, 6.838598] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = 20.3966, electric dipole moment = 18.3169, electric charge = 6.8386?", + "a": "23.07501147805773", + "valid": true, + "kind": "compute", + "expect": 23.07501147805773, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [20.396558, 18.316867, 6.838598] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the positively charged particle for a position of the negatively charged particle of 185.886, an electric dipole moment of 13.2373 and an electric charge of 4.71941, please.", + "a": "188.69113560192662", + "valid": true, + "kind": "compute", + "expect": 188.69113560192662, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [185.886273, 13.237311, 4.719415] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the negatively charged particle is 185.886, electric dipole moment is 13.2373 and the electric charge is 4.71941, what is the position of the positively charged particle?", + "a": "188.69113560192662", + "valid": true, + "kind": "compute", + "expect": 188.69113560192662, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [185.886273, 13.237311, 4.719415] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = 9.1061, electric dipole moment = 24.5721, electric charge = 108.451?", + "a": "9.332677591533786", + "valid": true, + "kind": "compute", + "expect": 9.332677591533786, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [9.106104, 24.572086, 108.450792] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "I need the position of the positively charged particle for a position of the negatively charged particle of 9.1061, an electric dipole moment of 24.5721 and an electric charge of 108.451, please.", + "a": "9.332677591533786", + "valid": true, + "kind": "compute", + "expect": 9.332677591533786, + "dtype": "quantity", + "unit": "m", + "why": "position of the positively charged particle for [9.106104, 24.572086, 108.450792] (the system electric dipole moment (Wikidata Q735135))" + }, + { + "q": "If the position of the negatively charged particle is 17.7888 and the electric dipole moment is 167.625, what is the position of the positively charged particle?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = 21.511, electric dipole moment = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric charge is not given" + }, + { + "q": "Do you know the position of the positively charged particle of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the position of the positively charged particle of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the position of the positively charged particle given position of the negatively charged particle = -129.245, electric dipole moment = 1.18359, electric charge = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position of the negatively charged particle: no example had one" + }, + { + "q": "What is a typical position of the positively charged particle?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-position-of-the-positively-ch/program.py b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6afa5e9d669ef517bad8d8dbfdebdfebfe510af4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/program.py @@ -0,0 +1,7 @@ +"""position of the positively charged particle from position of the negatively charged particle, electric dipole moment, electric charge (electric dipole moment (Wikidata Q735135)) +The maths organ (systems.py): solved from the system q2 = q3*( q0 - q1 ); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(position_of_the_negatively_charged_particle, electric_dipole_moment, electric_charge): + return 1.0*position_of_the_negatively_charged_particle + 1.0*electric_dipole_moment/electric_charge diff --git a/root/organs10/physics/specialists/solved-position-of-the-positively-ch/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-of-the-positively-ch/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-position-vector-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-position-vector-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-position-vector-2/panel.json b/root/organs10/physics/specialists/solved-position-vector-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a2adb1c7ba36c4929fdbbc5848e2fbb3eeaddcc9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the position vector for angular momentum 107.961 and momentum 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [107.960666, 59.4105] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 107.961 and momentum of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [107.960666, 59.4105] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 169.527 and momentum 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [169.526958, 280.773702] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 169.527 and momentum of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [169.526958, 280.773702] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 1.91195 and momentum 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.911952, 82.240072] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 1.91195 and momentum of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.911952, 82.240072] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 1.64379 and momentum 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.643795, 252.709024] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 1.64379 and momentum of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.643795, 252.709024] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 18.3169 and momentum 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [18.316867, 6.838598] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 18.3169 and momentum of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [18.316867, 6.838598] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 156.502 and momentum 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [156.50181, 185.886273] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the position vector with angular momentum of 156.502 and momentum of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [156.50181, 185.886273] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the position vector for angular momentum 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the momentum is not given" + }, + { + "q": "Tell me the position vector with angular momentum of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the momentum is not given" + }, + { + "q": "What is the position vector of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the position vector of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the position vector with angular momentum of -1.91195 and momentum of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular momentum: no example had one" + }, + { + "q": "Which position vector is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the angular momentum is 8.50728 and the momentum is 17.7888, what is the position vector?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.507283, 17.788778] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the position vector given angular momentum = 8.50728, momentum = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.507283, 17.788778] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the position vector for an angular momentum of 8.24951 and a momentum of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.24951, 0.634021] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 8.24951 and the momentum is 0.634021, what is the position vector?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.24951, 0.634021] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the position vector given angular momentum = 0.318734, momentum = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.318734, 9.566071] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the position vector for an angular momentum of 0.318734 and a momentum of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.318734, 9.566071] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 0.671697 and the momentum is 14.2496, what is the position vector?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.671697, 14.249569] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the position vector given angular momentum = 0.671697, momentum = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.671697, 14.249569] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the position vector for an angular momentum of 21.7931 and a momentum of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [21.793126, 29.510609] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 21.7931 and the momentum is 29.5106, what is the position vector?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [21.793126, 29.510609] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the position vector given angular momentum = 153.15, momentum = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [153.149965, 18.595315] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the position vector for an angular momentum of 153.15 and a momentum of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [153.149965, 18.595315] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 8.50728, what is the position vector?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the momentum is not given" + }, + { + "q": "Could you work out the position vector given angular momentum = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the momentum is not given" + }, + { + "q": "Do you know the position vector of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the position vector of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the position vector given angular momentum = -0.318734, momentum = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular momentum: no example had one" + }, + { + "q": "What is a typical position vector?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-position-vector-2/program.py b/root/organs10/physics/specialists/solved-position-vector-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0563d594d8a58f5bde96cf5d0c8ab8b3a86d6113 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector-2/program.py @@ -0,0 +1,7 @@ +"""position vector from angular momentum, momentum (angular momentum (Wikidata Q161254)) +The maths organ (systems.py): solved from the system q0 = q1 * q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(angular_momentum, momentum): + return 1.0*angular_momentum/momentum diff --git a/root/organs10/physics/specialists/solved-position-vector-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-position-vector-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-position-vector/organ_formula_v2.py b/root/organs10/physics/specialists/solved-position-vector/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-position-vector/panel.json b/root/organs10/physics/specialists/solved-position-vector/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c234e64e2f0651b4d51d4823f759d3e93e33798a --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the position vector for moment of force 107.961 and force 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [107.960666, 59.4105] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 107.961 and force of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [107.960666, 59.4105] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 169.527 and force 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [169.526958, 280.773702] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 169.527 and force of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [169.526958, 280.773702] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 1.91195 and force 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.911952, 82.240072] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 1.91195 and force of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.911952, 82.240072] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 1.64379 and force 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.643795, 252.709024] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 1.64379 and force of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [1.643795, 252.709024] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 18.3169 and force 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [18.316867, 6.838598] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 18.3169 and force of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [18.316867, 6.838598] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 156.502 and force 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [156.50181, 185.886273] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the position vector with moment of force of 156.502 and force of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [156.50181, 185.886273] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the position vector for moment of force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Tell me the position vector with moment of force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "What is the position vector of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the position vector of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the position vector with moment of force of -1.91195 and force of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative moment of force: no example had one" + }, + { + "q": "Which position vector is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the moment of force is 8.50728 and the force is 17.7888, what is the position vector?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.507283, 17.788778] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the position vector given moment of force = 8.50728, force = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.507283, 17.788778] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the position vector for a moment of force of 8.24951 and a force of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.24951, 0.634021] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the moment of force is 8.24951 and the force is 0.634021, what is the position vector?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [8.24951, 0.634021] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the position vector given moment of force = 0.318734, force = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.318734, 9.566071] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the position vector for a moment of force of 0.318734 and a force of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.318734, 9.566071] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the moment of force is 0.671697 and the force is 14.2496, what is the position vector?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.671697, 14.249569] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the position vector given moment of force = 0.671697, force = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [0.671697, 14.249569] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the position vector for a moment of force of 21.7931 and a force of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [21.793126, 29.510609] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the moment of force is 21.7931 and the force is 29.5106, what is the position vector?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [21.793126, 29.510609] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the position vector given moment of force = 153.15, force = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [153.149965, 18.595315] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the position vector for a moment of force of 153.15 and a force of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "position vector for [153.149965, 18.595315] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the moment of force is 8.50728, what is the position vector?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Could you work out the position vector given moment of force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Do you know the position vector of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the position vector of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the position vector given moment of force = -0.318734, force = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative moment of force: no example had one" + }, + { + "q": "What is a typical position vector?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-position-vector/program.py b/root/organs10/physics/specialists/solved-position-vector/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2beec92f722cd41f14060085fd18651c86b509c3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector/program.py @@ -0,0 +1,7 @@ +"""position vector from moment of force, force (moment of force (Wikidata Q17232562)) +The maths organ (systems.py): solved from the system q0 = q1 * q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(moment_of_force, force): + return 1.0*moment_of_force/force diff --git a/root/organs10/physics/specialists/solved-position-vector/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-position-vector/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-position-vector/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-positive-pressure/organ_formula_v2.py b/root/organs10/physics/specialists/solved-positive-pressure/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-positive-pressure/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-positive-pressure/panel.json b/root/organs10/physics/specialists/solved-positive-pressure/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a38f3cb67b3af36c266c516e1cf551382830f4a3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-positive-pressure/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the positive pressure for ambient pressure 8.50728 and pressure 17.7888?", + "a": "9.281495473483474", + "valid": true, + "kind": "compute", + "expect": 9.281495473483474, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [8.507283, 17.788778] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 8.50728 and pressure of 17.7888.", + "a": "9.281495473483474", + "valid": true, + "kind": "compute", + "expect": 9.281495473483474, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [8.507283, 17.788778] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 6.34623 and pressure 21.511?", + "a": "15.164790256952909", + "valid": true, + "kind": "compute", + "expect": 15.164790256952909, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [6.346226, 21.511016] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 6.34623 and pressure of 21.511.", + "a": "15.164790256952909", + "valid": true, + "kind": "compute", + "expect": 15.164790256952909, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [6.346226, 21.511016] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 1.64379 and pressure 252.709?", + "a": "251.06522875466473", + "valid": true, + "kind": "compute", + "expect": 251.06522875466473, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [1.643795, 252.709024] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 1.64379 and pressure of 252.709.", + "a": "251.06522875466473", + "valid": true, + "kind": "compute", + "expect": 251.06522875466473, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [1.643795, 252.709024] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 21.7931 and pressure 29.5106?", + "a": "7.717482167609866", + "valid": true, + "kind": "compute", + "expect": 7.717482167609866, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [21.793126, 29.510609] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 21.7931 and pressure of 29.5106.", + "a": "7.717482167609866", + "valid": true, + "kind": "compute", + "expect": 7.717482167609866, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [21.793126, 29.510609] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 7.10705 and pressure 30.2507?", + "a": "23.143700093865256", + "valid": true, + "kind": "compute", + "expect": 23.143700093865256, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [7.107049, 30.250749] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 7.10705 and pressure of 30.2507.", + "a": "23.143700093865256", + "valid": true, + "kind": "compute", + "expect": 23.143700093865256, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [7.107049, 30.250749] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 0.869111 and pressure 39.1753?", + "a": "38.3061515435122", + "valid": true, + "kind": "compute", + "expect": 38.3061515435122, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.869111, 39.175263] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 0.869111 and pressure of 39.1753.", + "a": "38.3061515435122", + "valid": true, + "kind": "compute", + "expect": 38.3061515435122, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.869111, 39.175263] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the positive pressure for ambient pressure 8.50728?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Tell me the positive pressure with ambient pressure of 6.34623.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "What is the positive pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the positive pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the positive pressure with ambient pressure of -1.64379 and pressure of 252.709.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative ambient pressure: no example had one" + }, + { + "q": "Which positive pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the ambient pressure is 169.527 and the pressure is 280.774, what is the positive pressure?", + "a": "111.24674440201241", + "valid": true, + "kind": "compute", + "expect": 111.24674440201241, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [169.526958, 280.773702] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = 169.527, pressure = 280.774?", + "a": "111.24674440201241", + "valid": true, + "kind": "compute", + "expect": 111.24674440201241, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [169.526958, 280.773702] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the positive pressure for an ambient pressure of 0.318734 and a pressure of 9.56607, please.", + "a": "9.24733694103161", + "valid": true, + "kind": "compute", + "expect": 9.24733694103161, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.318734, 9.566071] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 0.318734 and the pressure is 9.56607, what is the positive pressure?", + "a": "9.24733694103161", + "valid": true, + "kind": "compute", + "expect": 9.24733694103161, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.318734, 9.566071] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = 0.671697, pressure = 14.2496?", + "a": "13.57787211614313", + "valid": true, + "kind": "compute", + "expect": 13.57787211614313, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.671697, 14.249569] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the positive pressure for an ambient pressure of 0.671697 and a pressure of 14.2496, please.", + "a": "13.57787211614313", + "valid": true, + "kind": "compute", + "expect": 13.57787211614313, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [0.671697, 14.249569] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 156.502 and the pressure is 185.886, what is the positive pressure?", + "a": "29.38446301183552", + "valid": true, + "kind": "compute", + "expect": 29.38446301183552, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [156.50181, 185.886273] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = 156.502, pressure = 185.886?", + "a": "29.38446301183552", + "valid": true, + "kind": "compute", + "expect": 29.38446301183552, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [156.50181, 185.886273] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the positive pressure for an ambient pressure of 24.5721 and a pressure of 108.451, please.", + "a": "83.87870607231024", + "valid": true, + "kind": "compute", + "expect": 83.87870607231024, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [24.572086, 108.450792] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 24.5721 and the pressure is 108.451, what is the positive pressure?", + "a": "83.87870607231024", + "valid": true, + "kind": "compute", + "expect": 83.87870607231024, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [24.572086, 108.450792] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = 4.07774, pressure = 276.408?", + "a": "272.32983938133856", + "valid": true, + "kind": "compute", + "expect": 272.32983938133856, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [4.077743, 276.407582] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the positive pressure for an ambient pressure of 4.07774 and a pressure of 276.408, please.", + "a": "272.32983938133856", + "valid": true, + "kind": "compute", + "expect": 272.32983938133856, + "dtype": "quantity", + "unit": "Pa", + "why": "positive pressure for [4.077743, 276.407582] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 169.527, what is the positive pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = 0.318734?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Do you know the positive pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the positive pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the positive pressure given ambient pressure = -0.671697, pressure = 14.2496?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative ambient pressure: no example had one" + }, + { + "q": "What is a typical positive pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-positive-pressure/program.py b/root/organs10/physics/specialists/solved-positive-pressure/program.py new file mode 100644 index 0000000000000000000000000000000000000000..340da68b7e8d5c0cd0e7671f5365fd8785517096 --- /dev/null +++ b/root/organs10/physics/specialists/solved-positive-pressure/program.py @@ -0,0 +1,7 @@ +"""positive pressure from ambient pressure, pressure (positive pressure (Wikidata Q331466)) +The maths organ (systems.py): solved from the system q1 = q2 - q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(ambient_pressure, pressure): + return -1.0*ambient_pressure + 1.0*pressure diff --git a/root/organs10/physics/specialists/solved-positive-pressure/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-positive-pressure/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-positive-pressure/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-potential-energy-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-potential-energy-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-potential-energy-2/panel.json b/root/organs10/physics/specialists/solved-potential-energy-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e3995a6c1485a9e87e6c322233280ae8a1d1d1e2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the potential energy for mechanical energy 107.961 and kinetic energy 59.4105?", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [107.960666, 59.4105] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 107.961 and kinetic energy of 59.4105.", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [107.960666, 59.4105] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 157.223 and kinetic energy 35.6412?", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [157.22256, 35.641157] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 157.223 and kinetic energy of 35.6412.", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [157.22256, 35.641157] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 126.709 and kinetic energy 1.70503?", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [126.709252, 1.705032] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 126.709 and kinetic energy of 1.70503.", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [126.709252, 1.705032] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 41.6566 and kinetic energy 13.8779?", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [41.656639, 13.877867] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 41.6566 and kinetic energy of 13.8779.", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [41.656639, 13.877867] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 8.50341 and kinetic energy 0.58813?", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.503407, 0.58813] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 8.50341 and kinetic energy of 0.58813.", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.503407, 0.58813] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 223.509 and kinetic energy 17.3414?", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [223.508796, 17.341435] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the potential energy with mechanical energy of 223.509 and kinetic energy of 17.3414.", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [223.508796, 17.341435] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the potential energy for mechanical energy 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinetic energy is not given" + }, + { + "q": "Tell me the potential energy with mechanical energy of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinetic energy is not given" + }, + { + "q": "What is the potential energy of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the potential energy of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the potential energy with mechanical energy of -126.709 and kinetic energy of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical energy: no example had one" + }, + { + "q": "Which potential energy is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mechanical energy is 167.625 and the kinetic energy is 10.3291, what is the potential energy?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [167.624948, 10.329054] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the potential energy given mechanical energy = 167.625, kinetic energy = 10.3291?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [167.624948, 10.329054] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the potential energy for a mechanical energy of 13.999 and a kinetic energy of 0.348438, please.", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [13.999029, 0.348438] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the mechanical energy is 13.999 and the kinetic energy is 0.348438, what is the potential energy?", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [13.999029, 0.348438] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the potential energy given mechanical energy = 81.1967, kinetic energy = 6.98086?", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [81.196705, 6.980857] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the potential energy for a mechanical energy of 81.1967 and a kinetic energy of 6.98086, please.", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [81.196705, 6.980857] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the mechanical energy is 19.4474 and the kinetic energy is 4.51548, what is the potential energy?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [19.447357, 4.515475] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the potential energy given mechanical energy = 19.4474, kinetic energy = 4.51548?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [19.447357, 4.515475] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the potential energy for a mechanical energy of 13.2373 and a kinetic energy of 4.71941, please.", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [13.237311, 4.719415] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the mechanical energy is 13.2373 and the kinetic energy is 4.71941, what is the potential energy?", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [13.237311, 4.719415] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the potential energy given mechanical energy = 21.7946, kinetic energy = 9.1061?", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [21.794621, 9.106104] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the potential energy for a mechanical energy of 21.7946 and a kinetic energy of 9.1061, please.", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [21.794621, 9.106104] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the mechanical energy is 167.625, what is the potential energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinetic energy is not given" + }, + { + "q": "Could you work out the potential energy given mechanical energy = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinetic energy is not given" + }, + { + "q": "Do you know the potential energy of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the potential energy of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the potential energy given mechanical energy = -81.1967, kinetic energy = 6.98086?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical energy: no example had one" + }, + { + "q": "What is a typical potential energy?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-potential-energy-2/program.py b/root/organs10/physics/specialists/solved-potential-energy-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..70d041647788cbb2e684292cd8b494c649f336d8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy-2/program.py @@ -0,0 +1,7 @@ +"""potential energy from mechanical energy, kinetic energy (mechanical energy (Wikidata Q184550)) +The maths organ (systems.py): solved from the system q0 = q1 + q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mechanical_energy, kinetic_energy): + return -1.0*kinetic_energy + 1.0*mechanical_energy diff --git a/root/organs10/physics/specialists/solved-potential-energy-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-potential-energy-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-potential-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-potential-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-potential-energy/panel.json b/root/organs10/physics/specialists/solved-potential-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d4c3a232cb8187d9ebd2a8be306622d3f197e7a1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the potential energy for mass 107.961 and height 59.4105?", + "a": "62899.82526377075", + "valid": true, + "kind": "compute", + "expect": 62899.82526377075, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [107.960666, 59.4105] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 107.961 and height of 59.4105.", + "a": "62899.82526377075", + "valid": true, + "kind": "compute", + "expect": 62899.82526377075, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [107.960666, 59.4105] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 169.527 and height 280.774?", + "a": "466783.90361123066", + "valid": true, + "kind": "compute", + "expect": 466783.90361123066, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [169.526958, 280.773702] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 169.527 and height of 280.774.", + "a": "466783.90361123066", + "valid": true, + "kind": "compute", + "expect": 466783.90361123066, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [169.526958, 280.773702] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 1.91195 and height 82.2401?", + "a": "1541.9883330922135", + "valid": true, + "kind": "compute", + "expect": 1541.9883330922135, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [1.911952, 82.240072] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 1.91195 and height of 82.2401.", + "a": "1541.9883330922135", + "valid": true, + "kind": "compute", + "expect": 1541.9883330922135, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [1.911952, 82.240072] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 1.64379 and height 252.709?", + "a": "4073.701587615496", + "valid": true, + "kind": "compute", + "expect": 4073.701587615496, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [1.643795, 252.709024] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 1.64379 and height of 252.709.", + "a": "4073.701587615496", + "valid": true, + "kind": "compute", + "expect": 4073.701587615496, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [1.643795, 252.709024] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 18.3169 and height 6.8386?", + "a": "1228.3975651177632", + "valid": true, + "kind": "compute", + "expect": 1228.3975651177632, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [18.316867, 6.838598] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 18.3169 and height of 6.8386.", + "a": "1228.3975651177632", + "valid": true, + "kind": "compute", + "expect": 1228.3975651177632, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [18.316867, 6.838598] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 156.502 and height 185.886?", + "a": "285290.5321591355", + "valid": true, + "kind": "compute", + "expect": 285290.5321591355, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [156.50181, 185.886273] (the system Potential energy)" + }, + { + "q": "Tell me the potential energy with mass of 156.502 and height of 185.886.", + "a": "285290.5321591355", + "valid": true, + "kind": "compute", + "expect": 285290.5321591355, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [156.50181, 185.886273] (the system Potential energy)" + }, + { + "q": "What is the potential energy for mass 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Tell me the potential energy with mass of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "What is the potential energy of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the potential energy of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the potential energy with mass of -1.91195 and height of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass: no example had one" + }, + { + "q": "Which potential energy is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mass is 8.50728 and the height is 17.7888, what is the potential energy?", + "a": "1484.0811754764798", + "valid": true, + "kind": "compute", + "expect": 1484.0811754764798, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.507283, 17.788778] (the system Potential energy)" + }, + { + "q": "Could you work out the potential energy given mass = 8.50728, height = 17.7888?", + "a": "1484.0811754764798", + "valid": true, + "kind": "compute", + "expect": 1484.0811754764798, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.507283, 17.788778] (the system Potential energy)" + }, + { + "q": "I need the potential energy for a mass of 8.24951 and a height of 0.634021, please.", + "a": "51.29233217444131", + "valid": true, + "kind": "compute", + "expect": 51.29233217444131, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.24951, 0.634021] (the system Potential energy)" + }, + { + "q": "If the mass is 8.24951 and the height is 0.634021, what is the potential energy?", + "a": "51.29233217444131", + "valid": true, + "kind": "compute", + "expect": 51.29233217444131, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [8.24951, 0.634021] (the system Potential energy)" + }, + { + "q": "Could you work out the potential energy given mass = 0.318734, height = 9.56607?", + "a": "29.90079482449364", + "valid": true, + "kind": "compute", + "expect": 29.90079482449364, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [0.318734, 9.566071] (the system Potential energy)" + }, + { + "q": "I need the potential energy for a mass of 0.318734 and a height of 9.56607, please.", + "a": "29.90079482449364", + "valid": true, + "kind": "compute", + "expect": 29.90079482449364, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [0.318734, 9.566071] (the system Potential energy)" + }, + { + "q": "If the mass is 0.671697 and the height is 14.2496, what is the potential energy?", + "a": "93.86332869844775", + "valid": true, + "kind": "compute", + "expect": 93.86332869844775, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [0.671697, 14.249569] (the system Potential energy)" + }, + { + "q": "Could you work out the potential energy given mass = 0.671697, height = 14.2496?", + "a": "93.86332869844775", + "valid": true, + "kind": "compute", + "expect": 93.86332869844775, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [0.671697, 14.249569] (the system Potential energy)" + }, + { + "q": "I need the potential energy for a mass of 21.7931 and a height of 29.5106, please.", + "a": "6306.9353924587695", + "valid": true, + "kind": "compute", + "expect": 6306.9353924587695, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [21.793126, 29.510609] (the system Potential energy)" + }, + { + "q": "If the mass is 21.7931 and the height is 29.5106, what is the potential energy?", + "a": "6306.9353924587695", + "valid": true, + "kind": "compute", + "expect": 6306.9353924587695, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [21.793126, 29.510609] (the system Potential energy)" + }, + { + "q": "Could you work out the potential energy given mass = 153.15, height = 18.5953?", + "a": "27928.0831257017", + "valid": true, + "kind": "compute", + "expect": 27928.0831257017, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [153.149965, 18.595315] (the system Potential energy)" + }, + { + "q": "I need the potential energy for a mass of 153.15 and a height of 18.5953, please.", + "a": "27928.0831257017", + "valid": true, + "kind": "compute", + "expect": 27928.0831257017, + "dtype": "quantity", + "unit": "J", + "why": "potential energy for [153.149965, 18.595315] (the system Potential energy)" + }, + { + "q": "If the mass is 8.50728, what is the potential energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Could you work out the potential energy given mass = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Do you know the potential energy of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the potential energy of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the potential energy given mass = -0.318734, height = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass: no example had one" + }, + { + "q": "What is a typical potential energy?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-potential-energy/program.py b/root/organs10/physics/specialists/solved-potential-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..b0482137167b2380a236a85c09ea07b0647a1841 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy/program.py @@ -0,0 +1,7 @@ +"""potential energy from mass, height (Potential energy) +The maths organ (systems.py): solved from the system E = m*g*h; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass, height): + return 9.80665*height*mass diff --git a/root/organs10/physics/specialists/solved-potential-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-potential-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-potential-energy/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-10/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-10/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-10/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-10/panel.json b/root/organs10/physics/specialists/solved-power-10/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..bbdfda5f0b28c1096622b17f6cf40efc2c6f4629 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-10/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for swept area 107.961, wind speed 59.4105 and efficiency 5.77717?", + "a": "80108023.50322756", + "valid": true, + "kind": "compute", + "expect": 80108023.50322756, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 107.961, wind speed of 59.4105 and efficiency of 5.77717.", + "a": "80108023.50322756", + "valid": true, + "kind": "compute", + "expect": 80108023.50322756, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Wind power)" + }, + { + "q": "What is the power for swept area 85.2416, wind speed 160.878 and efficiency 2.69428?", + "a": "585725407.162425", + "valid": true, + "kind": "compute", + "expect": 585725407.162425, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 85.2416, wind speed of 160.878 and efficiency of 2.69428.", + "a": "585725407.162425", + "valid": true, + "kind": "compute", + "expect": 585725407.162425, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Wind power)" + }, + { + "q": "What is the power for swept area 45.6157, wind speed 4.97131 and efficiency 94.305?", + "a": "323718.0858301479", + "valid": true, + "kind": "compute", + "expect": 323718.0858301479, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 45.6157, wind speed of 4.97131 and efficiency of 94.305.", + "a": "323718.0858301479", + "valid": true, + "kind": "compute", + "expect": 323718.0858301479, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Wind power)" + }, + { + "q": "What is the power for swept area 10.5638, wind speed 198.839 and efficiency 0.671697?", + "a": "34166931.45774019", + "valid": true, + "kind": "compute", + "expect": 34166931.45774019, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 10.5638, wind speed of 198.839 and efficiency of 0.671697.", + "a": "34166931.45774019", + "valid": true, + "kind": "compute", + "expect": 34166931.45774019, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Wind power)" + }, + { + "q": "What is the power for swept area 21.7931, wind speed 29.5106 and efficiency 8.50341?", + "a": "2917112.0387778915", + "valid": true, + "kind": "compute", + "expect": 2917112.0387778915, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 21.7931, wind speed of 29.5106 and efficiency of 8.50341.", + "a": "2917112.0387778915", + "valid": true, + "kind": "compute", + "expect": 2917112.0387778915, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Wind power)" + }, + { + "q": "What is the power for swept area 223.509, wind speed 17.3414 and efficiency 7.10705?", + "a": "5073937.686841827", + "valid": true, + "kind": "compute", + "expect": 5073937.686841827, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Wind power)" + }, + { + "q": "Tell me the power with swept area of 223.509, wind speed of 17.3414 and efficiency of 7.10705.", + "a": "5073937.686841827", + "valid": true, + "kind": "compute", + "expect": 5073937.686841827, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Wind power)" + }, + { + "q": "What is the power for swept area 107.961 and wind speed 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Tell me the power with swept area of 85.2416 and wind speed of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with swept area of -45.6157, wind speed of 4.97131 and efficiency of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative swept area: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the swept area is 17.7888, wind speed is 167.625 and the efficiency is 10.3291, what is the power?", + "a": "530064532.23123807", + "valid": true, + "kind": "compute", + "expect": 530064532.23123807, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Wind power)" + }, + { + "q": "Could you work out the power given swept area = 17.7888, wind speed = 167.625, efficiency = 10.3291?", + "a": "530064532.23123807", + "valid": true, + "kind": "compute", + "expect": 530064532.23123807, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Wind power)" + }, + { + "q": "I need the power for a swept area of 21.511, a wind speed of 173.394 and an efficiency of 251.084, please.", + "a": "17245889369.481544", + "valid": true, + "kind": "compute", + "expect": 17245889369.481544, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Wind power)" + }, + { + "q": "If the swept area is 21.511, wind speed is 173.394 and the efficiency is 251.084, what is the power?", + "a": "17245889369.481544", + "valid": true, + "kind": "compute", + "expect": 17245889369.481544, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Wind power)" + }, + { + "q": "Could you work out the power given swept area = 129.245, wind speed = 1.18359, efficiency = 15.9416?", + "a": "2092.453592393323", + "valid": true, + "kind": "compute", + "expect": 2092.453592393323, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Wind power)" + }, + { + "q": "I need the power for a swept area of 129.245, a wind speed of 1.18359 and an efficiency of 15.9416, please.", + "a": "2092.453592393323", + "valid": true, + "kind": "compute", + "expect": 2092.453592393323, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Wind power)" + }, + { + "q": "If the swept area is 20.3966, wind speed is 18.3169 and the efficiency is 6.8386, what is the power?", + "a": "525029.412222472", + "valid": true, + "kind": "compute", + "expect": 525029.412222472, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Wind power)" + }, + { + "q": "Could you work out the power given swept area = 20.3966, wind speed = 18.3169, efficiency = 6.8386?", + "a": "525029.412222472", + "valid": true, + "kind": "compute", + "expect": 525029.412222472, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Wind power)" + }, + { + "q": "I need the power for a swept area of 185.886, a wind speed of 13.2373 and an efficiency of 4.71941, please.", + "a": "1246352.4959166243", + "valid": true, + "kind": "compute", + "expect": 1246352.4959166243, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Wind power)" + }, + { + "q": "If the swept area is 185.886, wind speed is 13.2373 and the efficiency is 4.71941, what is the power?", + "a": "1246352.4959166243", + "valid": true, + "kind": "compute", + "expect": 1246352.4959166243, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Wind power)" + }, + { + "q": "Could you work out the power given swept area = 9.1061, wind speed = 24.5721, efficiency = 108.451?", + "a": "8974236.071375575", + "valid": true, + "kind": "compute", + "expect": 8974236.071375575, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Wind power)" + }, + { + "q": "I need the power for a swept area of 9.1061, a wind speed of 24.5721 and an efficiency of 108.451, please.", + "a": "8974236.071375575", + "valid": true, + "kind": "compute", + "expect": 8974236.071375575, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Wind power)" + }, + { + "q": "If the swept area is 17.7888 and the wind speed is 167.625, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Could you work out the power given swept area = 21.511, wind speed = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given swept area = -129.245, wind speed = 1.18359, efficiency = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative swept area: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-10/program.py b/root/organs10/physics/specialists/solved-power-10/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d138cadd8fbeb3881026d44878d7e06d95e39556 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-10/program.py @@ -0,0 +1,7 @@ +"""power from swept area, wind speed, efficiency (Wind power) +The maths organ (systems.py): solved from the system P = r*A*v**3*e/2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(swept_area, wind_speed, efficiency): + return 0.6125*efficiency*swept_area*wind_speed**3 diff --git a/root/organs10/physics/specialists/solved-power-10/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-10/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-10/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-11/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-11/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-11/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-11/panel.json b/root/organs10/physics/specialists/solved-power-11/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..235c7d150332cfb32d8ea5bdac0f82aa11890eab --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-11/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for irradiance 107.961, panel area 59.4105 and efficiency 5.77717?", + "a": "37054.71743803604", + "valid": true, + "kind": "compute", + "expect": 37054.71743803604, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 107.961, panel area of 59.4105 and efficiency of 5.77717.", + "a": "37054.71743803604", + "valid": true, + "kind": "compute", + "expect": 37054.71743803604, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 85.2416, panel area 160.878 and efficiency 2.69428?", + "a": "36948.1133481491", + "valid": true, + "kind": "compute", + "expect": 36948.1133481491, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 85.2416, panel area of 160.878 and efficiency of 2.69428.", + "a": "36948.1133481491", + "valid": true, + "kind": "compute", + "expect": 36948.1133481491, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 45.6157, panel area 4.97131 and efficiency 94.305?", + "a": "21385.51027534082", + "valid": true, + "kind": "compute", + "expect": 21385.51027534082, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 45.6157, panel area of 4.97131 and efficiency of 94.305.", + "a": "21385.51027534082", + "valid": true, + "kind": "compute", + "expect": 21385.51027534082, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 10.5638, panel area 198.839 and efficiency 0.671697?", + "a": "1410.9022889506464", + "valid": true, + "kind": "compute", + "expect": 1410.9022889506464, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 10.5638, panel area of 198.839 and efficiency of 0.671697.", + "a": "1410.9022889506464", + "valid": true, + "kind": "compute", + "expect": 1410.9022889506464, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 21.7931, panel area 29.5106 and efficiency 8.50341?", + "a": "5468.782894065435", + "valid": true, + "kind": "compute", + "expect": 5468.782894065435, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 21.7931, panel area of 29.5106 and efficiency of 8.50341.", + "a": "5468.782894065435", + "valid": true, + "kind": "compute", + "expect": 5468.782894065435, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 223.509, panel area 17.3414 and efficiency 7.10705?", + "a": "27546.66146773027", + "valid": true, + "kind": "compute", + "expect": 27546.66146773027, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Solar power)" + }, + { + "q": "Tell me the power with irradiance of 223.509, panel area of 17.3414 and efficiency of 7.10705.", + "a": "27546.66146773027", + "valid": true, + "kind": "compute", + "expect": 27546.66146773027, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Solar power)" + }, + { + "q": "What is the power for irradiance 107.961 and panel area 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Tell me the power with irradiance of 85.2416 and panel area of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with irradiance of -45.6157, panel area of 4.97131 and efficiency of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative irradiance: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the irradiance is 17.7888, panel area is 167.625 and the efficiency is 10.3291, what is the power?", + "a": "30799.618802505258", + "valid": true, + "kind": "compute", + "expect": 30799.618802505258, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Solar power)" + }, + { + "q": "Could you work out the power given irradiance = 17.7888, panel area = 167.625, efficiency = 10.3291?", + "a": "30799.618802505258", + "valid": true, + "kind": "compute", + "expect": 30799.618802505258, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Solar power)" + }, + { + "q": "I need the power for an irradiance of 21.511, a panel area of 173.394 and an efficiency of 251.084, please.", + "a": "936511.6480251562", + "valid": true, + "kind": "compute", + "expect": 936511.6480251562, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Solar power)" + }, + { + "q": "If the irradiance is 21.511, panel area is 173.394 and the efficiency is 251.084, what is the power?", + "a": "936511.6480251562", + "valid": true, + "kind": "compute", + "expect": 936511.6480251562, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Solar power)" + }, + { + "q": "Could you work out the power given irradiance = 129.245, panel area = 1.18359, efficiency = 15.9416?", + "a": "2438.6371902755973", + "valid": true, + "kind": "compute", + "expect": 2438.6371902755973, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Solar power)" + }, + { + "q": "I need the power for an irradiance of 129.245, a panel area of 1.18359 and an efficiency of 15.9416, please.", + "a": "2438.6371902755973", + "valid": true, + "kind": "compute", + "expect": 2438.6371902755973, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Solar power)" + }, + { + "q": "If the irradiance is 20.3966, panel area is 18.3169 and the efficiency is 6.8386, what is the power?", + "a": "2554.907347285691", + "valid": true, + "kind": "compute", + "expect": 2554.907347285691, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Solar power)" + }, + { + "q": "Could you work out the power given irradiance = 20.3966, panel area = 18.3169, efficiency = 6.8386?", + "a": "2554.907347285691", + "valid": true, + "kind": "compute", + "expect": 2554.907347285691, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Solar power)" + }, + { + "q": "I need the power for an irradiance of 185.886, a panel area of 13.2373 and an efficiency of 4.71941, please.", + "a": "11612.754502579606", + "valid": true, + "kind": "compute", + "expect": 11612.754502579606, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Solar power)" + }, + { + "q": "If the irradiance is 185.886, panel area is 13.2373 and the efficiency is 4.71941, what is the power?", + "a": "11612.754502579606", + "valid": true, + "kind": "compute", + "expect": 11612.754502579606, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Solar power)" + }, + { + "q": "Could you work out the power given irradiance = 9.1061, panel area = 24.5721, efficiency = 108.451?", + "a": "24266.511866047756", + "valid": true, + "kind": "compute", + "expect": 24266.511866047756, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Solar power)" + }, + { + "q": "I need the power for an irradiance of 9.1061, a panel area of 24.5721 and an efficiency of 108.451, please.", + "a": "24266.511866047756", + "valid": true, + "kind": "compute", + "expect": 24266.511866047756, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Solar power)" + }, + { + "q": "If the irradiance is 17.7888 and the panel area is 167.625, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Could you work out the power given irradiance = 21.511, panel area = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given irradiance = -129.245, panel area = 1.18359, efficiency = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative irradiance: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-11/program.py b/root/organs10/physics/specialists/solved-power-11/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3106c077fcbbfa7221e306a55601580b08646771 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-11/program.py @@ -0,0 +1,7 @@ +"""power from irradiance, panel area, efficiency (Solar power) +The maths organ (systems.py): solved from the system P = G*A*e; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(irradiance, panel_area, efficiency): + return 1.0*efficiency*irradiance*panel_area diff --git a/root/organs10/physics/specialists/solved-power-11/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-11/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-11/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-12/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-12/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-12/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-12/panel.json b/root/organs10/physics/specialists/solved-power-12/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ebeba15b340ba2159d5577db1738dd6222a19c18 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-12/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for radiant efficiency 107.961 and radiant flux 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 107.961 and radiant flux of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 169.527 and radiant flux 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 169.527 and radiant flux of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 1.91195 and radiant flux 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 1.91195 and radiant flux of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 1.64379 and radiant flux 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 1.64379 and radiant flux of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 18.3169 and radiant flux 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 18.3169 and radiant flux of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 156.502 and radiant flux 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the power with radiant efficiency of 156.502 and radiant flux of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the power for radiant efficiency 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant flux is not given" + }, + { + "q": "Tell me the power with radiant efficiency of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant flux is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with radiant efficiency of -1.91195 and radiant flux of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant efficiency: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiant efficiency is 8.50728 and the radiant flux is 17.7888, what is the power?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the power given radiant efficiency = 8.50728, radiant flux = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the power for a radiant efficiency of 8.24951 and a radiant flux of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 8.24951 and the radiant flux is 0.634021, what is the power?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the power given radiant efficiency = 0.318734, radiant flux = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the power for a radiant efficiency of 0.318734 and a radiant flux of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 0.671697 and the radiant flux is 14.2496, what is the power?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the power given radiant efficiency = 0.671697, radiant flux = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the power for a radiant efficiency of 21.7931 and a radiant flux of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 21.7931 and the radiant flux is 29.5106, what is the power?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the power given radiant efficiency = 153.15, radiant flux = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the power for a radiant efficiency of 153.15 and a radiant flux of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant flux is not given" + }, + { + "q": "Could you work out the power given radiant efficiency = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant flux is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given radiant efficiency = -0.318734, radiant flux = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant efficiency: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-12/program.py b/root/organs10/physics/specialists/solved-power-12/program.py new file mode 100644 index 0000000000000000000000000000000000000000..97d080ba99dd65053167a3127fb7b4551a15c285 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-12/program.py @@ -0,0 +1,7 @@ +"""power from radiant efficiency, radiant flux (radiant efficiency (Wikidata Q7962586)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiant_efficiency, radiant_flux): + return 1.0*radiant_flux/radiant_efficiency diff --git a/root/organs10/physics/specialists/solved-power-12/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-12/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-12/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-13/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-13/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-13/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-13/panel.json b/root/organs10/physics/specialists/solved-power-13/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..bfd1bb3a6d6a1d22c204ab64a740f82fac91d495 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-13/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for moment of force 107.961 and angular velocity 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 107.961 and angular velocity of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 169.527 and angular velocity 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 169.527 and angular velocity of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 1.91195 and angular velocity 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 1.91195 and angular velocity of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 1.64379 and angular velocity 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 1.64379 and angular velocity of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 18.3169 and angular velocity 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 18.3169 and angular velocity of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 156.502 and angular velocity 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the power with moment of force of 156.502 and angular velocity of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the power for moment of force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular velocity is not given" + }, + { + "q": "Tell me the power with moment of force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular velocity is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with moment of force of -1.91195 and angular velocity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative moment of force: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the moment of force is 8.50728 and the angular velocity is 17.7888, what is the power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the power given moment of force = 8.50728, angular velocity = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the power for a moment of force of 8.24951 and an angular velocity of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the moment of force is 8.24951 and the angular velocity is 0.634021, what is the power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the power given moment of force = 0.318734, angular velocity = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the power for a moment of force of 0.318734 and an angular velocity of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the moment of force is 0.671697 and the angular velocity is 14.2496, what is the power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the power given moment of force = 0.671697, angular velocity = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the power for a moment of force of 21.7931 and an angular velocity of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the moment of force is 21.7931 and the angular velocity is 29.5106, what is the power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the power given moment of force = 153.15, angular velocity = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the power for a moment of force of 153.15 and an angular velocity of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the moment of force is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular velocity is not given" + }, + { + "q": "Could you work out the power given moment of force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular velocity is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given moment of force = -0.318734, angular velocity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative moment of force: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-13/program.py b/root/organs10/physics/specialists/solved-power-13/program.py new file mode 100644 index 0000000000000000000000000000000000000000..14a2df9ab43e430286aa1a18cd5b1977bcebb737 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-13/program.py @@ -0,0 +1,7 @@ +"""power from moment of force, angular velocity (power from torque (Wikidata Q104145185)) +The maths organ (systems.py): solved from the system q2 = q0 * q1; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(moment_of_force, angular_velocity): + return 1.0*angular_velocity*moment_of_force diff --git a/root/organs10/physics/specialists/solved-power-13/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-13/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-13/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-2/panel.json b/root/organs10/physics/specialists/solved-power-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d158299a329d1fbd263c7e87bd79097d0b667674 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for efficiency 107.961, flow 59.4105 and head 5.77717?", + "a": "363382644.7637161", + "valid": true, + "kind": "compute", + "expect": 363382644.7637161, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 107.961, flow of 59.4105 and head of 5.77717.", + "a": "363382644.7637161", + "valid": true, + "kind": "compute", + "expect": 363382644.7637161, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105, 5.777165] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 85.2416, flow 160.878 and head 2.69428?", + "a": "362337215.7656263", + "valid": true, + "kind": "compute", + "expect": 362337215.7656263, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 85.2416, flow of 160.878 and head of 2.69428.", + "a": "362337215.7656263", + "valid": true, + "kind": "compute", + "expect": 362337215.7656263, + "dtype": "quantity", + "unit": "W", + "why": "power for [85.241623, 160.878442, 2.69428] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 45.6157, flow 4.97131 and head 94.305?", + "a": "209720214.34167102", + "valid": true, + "kind": "compute", + "expect": 209720214.34167102, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 45.6157, flow of 4.97131 and head of 94.305.", + "a": "209720214.34167102", + "valid": true, + "kind": "compute", + "expect": 209720214.34167102, + "dtype": "quantity", + "unit": "W", + "why": "power for [45.61567, 4.971307, 94.305046] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 10.5638, flow 198.839 and head 0.671697?", + "a": "13836224.931937855", + "valid": true, + "kind": "compute", + "expect": 13836224.931937855, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 10.5638, flow of 198.839 and head of 0.671697.", + "a": "13836224.931937855", + "valid": true, + "kind": "compute", + "expect": 13836224.931937855, + "dtype": "quantity", + "unit": "W", + "why": "power for [10.563843, 198.838955, 0.671697] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 21.7931, flow 29.5106 and head 8.50341?", + "a": "53630439.7680868", + "valid": true, + "kind": "compute", + "expect": 53630439.7680868, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 21.7931, flow of 29.5106 and head of 8.50341.", + "a": "53630439.7680868", + "valid": true, + "kind": "compute", + "expect": 53630439.7680868, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609, 8.503407] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 223.509, flow 17.3414 and head 7.10705?", + "a": "270140467.68251705", + "valid": true, + "kind": "compute", + "expect": 270140467.68251705, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Hydro power)" + }, + { + "q": "Tell me the power with efficiency of 223.509, flow of 17.3414 and head of 7.10705.", + "a": "270140467.68251705", + "valid": true, + "kind": "compute", + "expect": 270140467.68251705, + "dtype": "quantity", + "unit": "W", + "why": "power for [223.508796, 17.341435, 7.107049] (the system Hydro power)" + }, + { + "q": "What is the power for efficiency 107.961 and flow 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the head is not given" + }, + { + "q": "Tell me the power with efficiency of 85.2416 and flow of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the head is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with efficiency of -45.6157, flow of 4.97131 and head of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative efficiency: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the efficiency is 17.7888, flow is 167.625 and the head is 10.3291, what is the power?", + "a": "302041081.72958815", + "valid": true, + "kind": "compute", + "expect": 302041081.72958815, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Hydro power)" + }, + { + "q": "Could you work out the power given efficiency = 17.7888, flow = 167.625, head = 10.3291?", + "a": "302041081.72958815", + "valid": true, + "kind": "compute", + "expect": 302041081.72958815, + "dtype": "quantity", + "unit": "W", + "why": "power for [17.788778, 167.624948, 10.329054] (the system Hydro power)" + }, + { + "q": "I need the power for an efficiency of 21.511, a flow of 173.394 and a head of 251.084, please.", + "a": "9184041953.1059", + "valid": true, + "kind": "compute", + "expect": 9184041953.1059, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Hydro power)" + }, + { + "q": "If the efficiency is 21.511, flow is 173.394 and the head is 251.084, what is the power?", + "a": "9184041953.1059", + "valid": true, + "kind": "compute", + "expect": 9184041953.1059, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.511016, 173.393638, 251.084037] (the system Hydro power)" + }, + { + "q": "Could you work out the power given efficiency = 129.245, flow = 1.18359, head = 15.9416?", + "a": "23914861.40201618", + "valid": true, + "kind": "compute", + "expect": 23914861.40201618, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Hydro power)" + }, + { + "q": "I need the power for an efficiency of 129.245, a flow of 1.18359 and a head of 15.9416, please.", + "a": "23914861.40201618", + "valid": true, + "kind": "compute", + "expect": 23914861.40201618, + "dtype": "quantity", + "unit": "W", + "why": "power for [129.244984, 1.18359, 15.941612] (the system Hydro power)" + }, + { + "q": "If the efficiency is 20.3966, flow is 18.3169 and the head is 6.8386, what is the power?", + "a": "25055082.13725922", + "valid": true, + "kind": "compute", + "expect": 25055082.13725922, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Hydro power)" + }, + { + "q": "Could you work out the power given efficiency = 20.3966, flow = 18.3169, head = 6.8386?", + "a": "25055082.13725922", + "valid": true, + "kind": "compute", + "expect": 25055082.13725922, + "dtype": "quantity", + "unit": "W", + "why": "power for [20.396558, 18.316867, 6.838598] (the system Hydro power)" + }, + { + "q": "I need the power for an efficiency of 185.886, a flow of 13.2373 and a head of 4.71941, please.", + "a": "113882218.9427223", + "valid": true, + "kind": "compute", + "expect": 113882218.9427223, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Hydro power)" + }, + { + "q": "If the efficiency is 185.886, flow is 13.2373 and the head is 4.71941, what is the power?", + "a": "113882218.9427223", + "valid": true, + "kind": "compute", + "expect": 113882218.9427223, + "dtype": "quantity", + "unit": "W", + "why": "power for [185.886273, 13.237311, 4.719415] (the system Hydro power)" + }, + { + "q": "Could you work out the power given efficiency = 9.1061, flow = 24.5721, head = 108.451?", + "a": "237973188.5911772", + "valid": true, + "kind": "compute", + "expect": 237973188.5911772, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Hydro power)" + }, + { + "q": "I need the power for an efficiency of 9.1061, a flow of 24.5721 and a head of 108.451, please.", + "a": "237973188.5911772", + "valid": true, + "kind": "compute", + "expect": 237973188.5911772, + "dtype": "quantity", + "unit": "W", + "why": "power for [9.106104, 24.572086, 108.450792] (the system Hydro power)" + }, + { + "q": "If the efficiency is 17.7888 and the flow is 167.625, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the head is not given" + }, + { + "q": "Could you work out the power given efficiency = 21.511, flow = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the head is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given efficiency = -129.245, flow = 1.18359, head = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative efficiency: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-2/program.py b/root/organs10/physics/specialists/solved-power-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..17d2d884453d2b1a849cf5530b59f04b7b8a98a9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-2/program.py @@ -0,0 +1,7 @@ +"""power from efficiency, flow, head (Hydro power) +The maths organ (systems.py): solved from the system P = e*r*g*Q*H; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(efficiency, flow, head): + return 9806.65*efficiency*flow*head diff --git a/root/organs10/physics/specialists/solved-power-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-3/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-3/panel.json b/root/organs10/physics/specialists/solved-power-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c9e295705f8a9777f7ecf92f0f0933bcd47be00b --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for voltage 107.961 and current 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 107.961 and current of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Electric power)" + }, + { + "q": "What is the power for voltage 169.527 and current 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 169.527 and current of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Electric power)" + }, + { + "q": "What is the power for voltage 1.91195 and current 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 1.91195 and current of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Electric power)" + }, + { + "q": "What is the power for voltage 1.64379 and current 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 1.64379 and current of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Electric power)" + }, + { + "q": "What is the power for voltage 18.3169 and current 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 18.3169 and current of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Electric power)" + }, + { + "q": "What is the power for voltage 156.502 and current 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Electric power)" + }, + { + "q": "Tell me the power with voltage of 156.502 and current of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Electric power)" + }, + { + "q": "What is the power for voltage 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Tell me the power with voltage of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with voltage of -1.91195 and current of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the voltage is 8.50728 and the current is 17.7888, what is the power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Electric power)" + }, + { + "q": "Could you work out the power given voltage = 8.50728, current = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Electric power)" + }, + { + "q": "I need the power for a voltage of 8.24951 and a current of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Electric power)" + }, + { + "q": "If the voltage is 8.24951 and the current is 0.634021, what is the power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Electric power)" + }, + { + "q": "Could you work out the power given voltage = 0.318734, current = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Electric power)" + }, + { + "q": "I need the power for a voltage of 0.318734 and a current of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Electric power)" + }, + { + "q": "If the voltage is 0.671697 and the current is 14.2496, what is the power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Electric power)" + }, + { + "q": "Could you work out the power given voltage = 0.671697, current = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Electric power)" + }, + { + "q": "I need the power for a voltage of 21.7931 and a current of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Electric power)" + }, + { + "q": "If the voltage is 21.7931 and the current is 29.5106, what is the power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Electric power)" + }, + { + "q": "Could you work out the power given voltage = 153.15, current = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Electric power)" + }, + { + "q": "I need the power for a voltage of 153.15 and a current of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Electric power)" + }, + { + "q": "If the voltage is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Could you work out the power given voltage = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given voltage = -0.318734, current = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-3/program.py b/root/organs10/physics/specialists/solved-power-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..e9588d8e5599b77018dd4b6b4465086d5a79efdc --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-3/program.py @@ -0,0 +1,7 @@ +"""power from voltage, current (Electric power) +The maths organ (systems.py): solved from the system P = U*I; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(voltage, current): + return 1.0*current*voltage diff --git a/root/organs10/physics/specialists/solved-power-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-3/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-4/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-4/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-4/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-4/panel.json b/root/organs10/physics/specialists/solved-power-4/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..872d882fe1e63031a1c5f84a55565bb4cecd19bf --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-4/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power in MW for power 107.961?", + "a": "0.00010796066588996202", + "valid": true, + "kind": "compute", + "expect": 0.00010796066588996202, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [107.960666] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 107.961.", + "a": "0.00010796066588996202", + "valid": true, + "kind": "compute", + "expect": 0.00010796066588996202, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [107.960666] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW for power 22.652?", + "a": "2.2652022796855792e-05", + "valid": true, + "kind": "compute", + "expect": 2.2652022796855792e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [22.652023] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 22.652.", + "a": "2.2652022796855792e-05", + "valid": true, + "kind": "compute", + "expect": 2.2652022796855792e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [22.652023] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW for power 173.394?", + "a": "0.0001733936384053025", + "valid": true, + "kind": "compute", + "expect": 0.0001733936384053025, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [173.393638] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 173.394.", + "a": "0.0001733936384053025", + "valid": true, + "kind": "compute", + "expect": 0.0001733936384053025, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [173.393638] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW for power 126.709?", + "a": "0.00012670925180018237", + "valid": true, + "kind": "compute", + "expect": 0.00012670925180018237, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [126.709252] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 126.709.", + "a": "0.00012670925180018237", + "valid": true, + "kind": "compute", + "expect": 0.00012670925180018237, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [126.709252] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW for power 0.671697?", + "a": "6.716971997941935e-07", + "valid": true, + "kind": "compute", + "expect": 6.716971997941935e-07, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [0.671697] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 0.671697.", + "a": "6.716971997941935e-07", + "valid": true, + "kind": "compute", + "expect": 6.716971997941935e-07, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [0.671697] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW for power 1.16997?", + "a": "1.1699680059779359e-06", + "valid": true, + "kind": "compute", + "expect": 1.1699680059779359e-06, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [1.169968] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in MW with power of 1.16997.", + "a": "1.1699680059779359e-06", + "valid": true, + "kind": "compute", + "expect": 1.1699680059779359e-06, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [1.169968] (the system Megawatts and watts)" + }, + { + "q": "What is the power in MW?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the power in MW, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the power in MW of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power in MW of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power in MW with power of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which power in MW is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the power is 2.57003, what is the power in MW?", + "a": "2.570029913303644e-06", + "valid": true, + "kind": "compute", + "expect": 2.570029913303644e-06, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [2.57003] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in MW given power = 2.57003?", + "a": "2.570029913303644e-06", + "valid": true, + "kind": "compute", + "expect": 2.570029913303644e-06, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [2.57003] (the system Megawatts and watts)" + }, + { + "q": "I need the power in MW for a power of 48.921, please.", + "a": "4.892099086001184e-05", + "valid": true, + "kind": "compute", + "expect": 4.892099086001184e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [48.920991] (the system Megawatts and watts)" + }, + { + "q": "If the power is 48.921, what is the power in MW?", + "a": "4.892099086001184e-05", + "valid": true, + "kind": "compute", + "expect": 4.892099086001184e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [48.920991] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in MW given power = 0.348438?", + "a": "3.484376696300305e-07", + "valid": true, + "kind": "compute", + "expect": 3.484376696300305e-07, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [0.348438] (the system Megawatts and watts)" + }, + { + "q": "I need the power in MW for a power of 0.348438, please.", + "a": "3.484376696300305e-07", + "valid": true, + "kind": "compute", + "expect": 3.484376696300305e-07, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [0.348438] (the system Megawatts and watts)" + }, + { + "q": "If the power is 252.709, what is the power in MW?", + "a": "0.0002527090242495275", + "valid": true, + "kind": "compute", + "expect": 0.0002527090242495275, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [252.709024] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in MW given power = 252.709?", + "a": "0.0002527090242495275", + "valid": true, + "kind": "compute", + "expect": 0.0002527090242495275, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [252.709024] (the system Megawatts and watts)" + }, + { + "q": "I need the power in MW for a power of 20.3966, please.", + "a": "2.039655796196344e-05", + "valid": true, + "kind": "compute", + "expect": 2.039655796196344e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [20.396558] (the system Megawatts and watts)" + }, + { + "q": "If the power is 20.3966, what is the power in MW?", + "a": "2.039655796196344e-05", + "valid": true, + "kind": "compute", + "expect": 2.039655796196344e-05, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [20.396558] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in MW given power = 134.993?", + "a": "0.000134992957580738", + "valid": true, + "kind": "compute", + "expect": 0.000134992957580738, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [134.992958] (the system Megawatts and watts)" + }, + { + "q": "I need the power in MW for a power of 134.993, please.", + "a": "0.000134992957580738", + "valid": true, + "kind": "compute", + "expect": 0.000134992957580738, + "dtype": "quantity", + "unit": "MW", + "why": "power in MW for [134.992958] (the system Megawatts and watts)" + }, + { + "q": "I need the power in MW, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Can you tell me the power in MW?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the power in MW of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power in MW of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power in MW given power = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "What is a typical power in MW?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-4/program.py b/root/organs10/physics/specialists/solved-power-4/program.py new file mode 100644 index 0000000000000000000000000000000000000000..f53ab8c15316f869e5286fdd297615eb91a5e7e0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-4/program.py @@ -0,0 +1,7 @@ +"""power from power (Megawatts and watts) +The maths organ (systems.py): solved from the system M = W; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(power): + return 1.0e-6*power diff --git a/root/organs10/physics/specialists/solved-power-4/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-4/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-4/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-5/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-5/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-5/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-5/panel.json b/root/organs10/physics/specialists/solved-power-5/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7791540a21fda20d03f2288cae9435c4cbdf5b98 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-5/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power in W for power 107.961?", + "a": "107960665.88996202", + "valid": true, + "kind": "compute", + "expect": 107960665.88996202, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [107.960666] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 107.961.", + "a": "107960665.88996202", + "valid": true, + "kind": "compute", + "expect": 107960665.88996202, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [107.960666] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W for power 22.652?", + "a": "22652022.796855792", + "valid": true, + "kind": "compute", + "expect": 22652022.796855792, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [22.652023] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 22.652.", + "a": "22652022.796855792", + "valid": true, + "kind": "compute", + "expect": 22652022.796855792, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [22.652023] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W for power 173.394?", + "a": "173393638.40530252", + "valid": true, + "kind": "compute", + "expect": 173393638.40530252, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [173.393638] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 173.394.", + "a": "173393638.40530252", + "valid": true, + "kind": "compute", + "expect": 173393638.40530252, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [173.393638] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W for power 126.709?", + "a": "126709251.80018237", + "valid": true, + "kind": "compute", + "expect": 126709251.80018237, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [126.709252] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 126.709.", + "a": "126709251.80018237", + "valid": true, + "kind": "compute", + "expect": 126709251.80018237, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [126.709252] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W for power 0.671697?", + "a": "671697.1997941935", + "valid": true, + "kind": "compute", + "expect": 671697.1997941935, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.671697] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 0.671697.", + "a": "671697.1997941935", + "valid": true, + "kind": "compute", + "expect": 671697.1997941935, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.671697] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W for power 1.16997?", + "a": "1169968.0059779359", + "valid": true, + "kind": "compute", + "expect": 1169968.0059779359, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [1.169968] (the system Megawatts and watts)" + }, + { + "q": "Tell me the power in W with power of 1.16997.", + "a": "1169968.0059779359", + "valid": true, + "kind": "compute", + "expect": 1169968.0059779359, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [1.169968] (the system Megawatts and watts)" + }, + { + "q": "What is the power in W?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the power in W, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the power in W of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power in W of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power in W with power of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which power in W is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the power is 2.57003, what is the power in W?", + "a": "2570029.913303644", + "valid": true, + "kind": "compute", + "expect": 2570029.913303644, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [2.57003] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 2.57003?", + "a": "2570029.913303644", + "valid": true, + "kind": "compute", + "expect": 2570029.913303644, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [2.57003] (the system Megawatts and watts)" + }, + { + "q": "I need the power in W for a power of 48.921, please.", + "a": "48920990.86001183", + "valid": true, + "kind": "compute", + "expect": 48920990.86001183, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [48.920991] (the system Megawatts and watts)" + }, + { + "q": "If the power is 48.921, what is the power in W?", + "a": "48920990.86001183", + "valid": true, + "kind": "compute", + "expect": 48920990.86001183, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [48.920991] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 0.348438?", + "a": "348437.66963003046", + "valid": true, + "kind": "compute", + "expect": 348437.66963003046, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.348438] (the system Megawatts and watts)" + }, + { + "q": "I need the power in W for a power of 0.348438, please.", + "a": "348437.66963003046", + "valid": true, + "kind": "compute", + "expect": 348437.66963003046, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.348438] (the system Megawatts and watts)" + }, + { + "q": "If the power is 252.709, what is the power in W?", + "a": "252709024.2495275", + "valid": true, + "kind": "compute", + "expect": 252709024.2495275, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [252.709024] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 252.709?", + "a": "252709024.2495275", + "valid": true, + "kind": "compute", + "expect": 252709024.2495275, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [252.709024] (the system Megawatts and watts)" + }, + { + "q": "I need the power in W for a power of 20.3966, please.", + "a": "20396557.961963437", + "valid": true, + "kind": "compute", + "expect": 20396557.961963437, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [20.396558] (the system Megawatts and watts)" + }, + { + "q": "If the power is 20.3966, what is the power in W?", + "a": "20396557.961963437", + "valid": true, + "kind": "compute", + "expect": 20396557.961963437, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [20.396558] (the system Megawatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 134.993?", + "a": "134992957.580738", + "valid": true, + "kind": "compute", + "expect": 134992957.580738, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [134.992958] (the system Megawatts and watts)" + }, + { + "q": "I need the power in W for a power of 134.993, please.", + "a": "134992957.580738", + "valid": true, + "kind": "compute", + "expect": 134992957.580738, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [134.992958] (the system Megawatts and watts)" + }, + { + "q": "I need the power in W, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Can you tell me the power in W?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the power in W of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power in W of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power in W given power = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "What is a typical power in W?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-5/program.py b/root/organs10/physics/specialists/solved-power-5/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6e4a57eb749257bc1b1760279ca2fc48e222ad --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-5/program.py @@ -0,0 +1,7 @@ +"""power from power (Megawatts and watts) +The maths organ (systems.py): solved from the system M = W; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(power): + return 1000000.0*power diff --git a/root/organs10/physics/specialists/solved-power-5/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-5/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-5/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-6/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-6/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-6/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-6/panel.json b/root/organs10/physics/specialists/solved-power-6/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d37bd33d3109d92a0183959898f707f28adfb66d --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-6/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for energy 107.961 and time 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kW", + "why": "power for [107.960666, 59.4105] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 107.961 and time of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kW", + "why": "power for [107.960666, 59.4105] (the system Energy over time)" + }, + { + "q": "What is the power for energy 169.527 and time 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kW", + "why": "power for [169.526958, 280.773702] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 169.527 and time of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kW", + "why": "power for [169.526958, 280.773702] (the system Energy over time)" + }, + { + "q": "What is the power for energy 1.91195 and time 82.2401?", + "a": "0.0232484203885924", + "valid": true, + "kind": "compute", + "expect": 0.0232484203885924, + "dtype": "quantity", + "unit": "kW", + "why": "power for [1.911952, 82.240072] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 1.91195 and time of 82.2401.", + "a": "0.0232484203885924", + "valid": true, + "kind": "compute", + "expect": 0.0232484203885924, + "dtype": "quantity", + "unit": "kW", + "why": "power for [1.911952, 82.240072] (the system Energy over time)" + }, + { + "q": "What is the power for energy 1.64379 and time 252.709?", + "a": "0.006504696457692341", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692341, + "dtype": "quantity", + "unit": "kW", + "why": "power for [1.643795, 252.709024] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 1.64379 and time of 252.709.", + "a": "0.006504696457692341", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692341, + "dtype": "quantity", + "unit": "kW", + "why": "power for [1.643795, 252.709024] (the system Energy over time)" + }, + { + "q": "What is the power for energy 18.3169 and time 6.8386?", + "a": "2.678453516094291", + "valid": true, + "kind": "compute", + "expect": 2.678453516094291, + "dtype": "quantity", + "unit": "kW", + "why": "power for [18.316867, 6.838598] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 18.3169 and time of 6.8386.", + "a": "2.678453516094291", + "valid": true, + "kind": "compute", + "expect": 2.678453516094291, + "dtype": "quantity", + "unit": "kW", + "why": "power for [18.316867, 6.838598] (the system Energy over time)" + }, + { + "q": "What is the power for energy 156.502 and time 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kW", + "why": "power for [156.50181, 185.886273] (the system Energy over time)" + }, + { + "q": "Tell me the power with energy of 156.502 and time of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kW", + "why": "power for [156.50181, 185.886273] (the system Energy over time)" + }, + { + "q": "What is the power for energy 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Tell me the power with energy of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with energy of -1.91195 and time of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative energy: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the energy is 8.50728 and the time is 17.7888, what is the power?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kW", + "why": "power for [8.507283, 17.788778] (the system Energy over time)" + }, + { + "q": "Could you work out the power given energy = 8.50728, time = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kW", + "why": "power for [8.507283, 17.788778] (the system Energy over time)" + }, + { + "q": "I need the power for an energy of 8.24951 and a time of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kW", + "why": "power for [8.24951, 0.634021] (the system Energy over time)" + }, + { + "q": "If the energy is 8.24951 and the time is 0.634021, what is the power?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kW", + "why": "power for [8.24951, 0.634021] (the system Energy over time)" + }, + { + "q": "Could you work out the power given energy = 0.318734, time = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kW", + "why": "power for [0.318734, 9.566071] (the system Energy over time)" + }, + { + "q": "I need the power for an energy of 0.318734 and a time of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kW", + "why": "power for [0.318734, 9.566071] (the system Energy over time)" + }, + { + "q": "If the energy is 0.671697 and the time is 14.2496, what is the power?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "kW", + "why": "power for [0.671697, 14.249569] (the system Energy over time)" + }, + { + "q": "Could you work out the power given energy = 0.671697, time = 14.2496?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "kW", + "why": "power for [0.671697, 14.249569] (the system Energy over time)" + }, + { + "q": "I need the power for an energy of 21.7931 and a time of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kW", + "why": "power for [21.793126, 29.510609] (the system Energy over time)" + }, + { + "q": "If the energy is 21.7931 and the time is 29.5106, what is the power?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kW", + "why": "power for [21.793126, 29.510609] (the system Energy over time)" + }, + { + "q": "Could you work out the power given energy = 153.15, time = 18.5953?", + "a": "8.235943368499308", + "valid": true, + "kind": "compute", + "expect": 8.235943368499308, + "dtype": "quantity", + "unit": "kW", + "why": "power for [153.149965, 18.595315] (the system Energy over time)" + }, + { + "q": "I need the power for an energy of 153.15 and a time of 18.5953, please.", + "a": "8.235943368499308", + "valid": true, + "kind": "compute", + "expect": 8.235943368499308, + "dtype": "quantity", + "unit": "kW", + "why": "power for [153.149965, 18.595315] (the system Energy over time)" + }, + { + "q": "If the energy is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Could you work out the power given energy = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given energy = -0.318734, time = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative energy: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-6/program.py b/root/organs10/physics/specialists/solved-power-6/program.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0bba5a989ed8d06660167338927be8c61eafcf --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-6/program.py @@ -0,0 +1,7 @@ +"""power from energy, time (Energy over time) +The maths organ (systems.py): solved from the system E = P*t; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(energy, time): + return 1.0*energy/time diff --git a/root/organs10/physics/specialists/solved-power-6/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-6/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-6/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-7/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-7/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-7/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-7/panel.json b/root/organs10/physics/specialists/solved-power-7/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..02eb94dacf72fd90a1e8d63f7eae78a1c6aa30aa --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-7/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power in kW for power 107.961?", + "a": "0.10796066588996202", + "valid": true, + "kind": "compute", + "expect": 0.10796066588996202, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [107.960666] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 107.961.", + "a": "0.10796066588996202", + "valid": true, + "kind": "compute", + "expect": 0.10796066588996202, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [107.960666] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW for power 22.652?", + "a": "0.022652022796855794", + "valid": true, + "kind": "compute", + "expect": 0.022652022796855794, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [22.652023] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 22.652.", + "a": "0.022652022796855794", + "valid": true, + "kind": "compute", + "expect": 0.022652022796855794, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [22.652023] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW for power 173.394?", + "a": "0.1733936384053025", + "valid": true, + "kind": "compute", + "expect": 0.1733936384053025, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [173.393638] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 173.394.", + "a": "0.1733936384053025", + "valid": true, + "kind": "compute", + "expect": 0.1733936384053025, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [173.393638] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW for power 126.709?", + "a": "0.12670925180018236", + "valid": true, + "kind": "compute", + "expect": 0.12670925180018236, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [126.709252] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 126.709.", + "a": "0.12670925180018236", + "valid": true, + "kind": "compute", + "expect": 0.12670925180018236, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [126.709252] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW for power 0.671697?", + "a": "0.0006716971997941935", + "valid": true, + "kind": "compute", + "expect": 0.0006716971997941935, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [0.671697] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 0.671697.", + "a": "0.0006716971997941935", + "valid": true, + "kind": "compute", + "expect": 0.0006716971997941935, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [0.671697] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW for power 1.16997?", + "a": "0.0011699680059779358", + "valid": true, + "kind": "compute", + "expect": 0.0011699680059779358, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [1.169968] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in kW with power of 1.16997.", + "a": "0.0011699680059779358", + "valid": true, + "kind": "compute", + "expect": 0.0011699680059779358, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [1.169968] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in kW?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the power in kW, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the power in kW of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power in kW of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power in kW with power of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which power in kW is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the power is 2.57003, what is the power in kW?", + "a": "0.002570029913303644", + "valid": true, + "kind": "compute", + "expect": 0.002570029913303644, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [2.57003] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in kW given power = 2.57003?", + "a": "0.002570029913303644", + "valid": true, + "kind": "compute", + "expect": 0.002570029913303644, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [2.57003] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in kW for a power of 48.921, please.", + "a": "0.04892099086001184", + "valid": true, + "kind": "compute", + "expect": 0.04892099086001184, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [48.920991] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 48.921, what is the power in kW?", + "a": "0.04892099086001184", + "valid": true, + "kind": "compute", + "expect": 0.04892099086001184, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [48.920991] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in kW given power = 0.348438?", + "a": "0.00034843766963003046", + "valid": true, + "kind": "compute", + "expect": 0.00034843766963003046, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [0.348438] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in kW for a power of 0.348438, please.", + "a": "0.00034843766963003046", + "valid": true, + "kind": "compute", + "expect": 0.00034843766963003046, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [0.348438] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 252.709, what is the power in kW?", + "a": "0.2527090242495275", + "valid": true, + "kind": "compute", + "expect": 0.2527090242495275, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [252.709024] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in kW given power = 252.709?", + "a": "0.2527090242495275", + "valid": true, + "kind": "compute", + "expect": 0.2527090242495275, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [252.709024] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in kW for a power of 20.3966, please.", + "a": "0.02039655796196344", + "valid": true, + "kind": "compute", + "expect": 0.02039655796196344, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [20.396558] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 20.3966, what is the power in kW?", + "a": "0.02039655796196344", + "valid": true, + "kind": "compute", + "expect": 0.02039655796196344, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [20.396558] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in kW given power = 134.993?", + "a": "0.13499295758073798", + "valid": true, + "kind": "compute", + "expect": 0.13499295758073798, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [134.992958] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in kW for a power of 134.993, please.", + "a": "0.13499295758073798", + "valid": true, + "kind": "compute", + "expect": 0.13499295758073798, + "dtype": "quantity", + "unit": "kW", + "why": "power in kW for [134.992958] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in kW, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Can you tell me the power in kW?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the power in kW of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power in kW of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power in kW given power = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "What is a typical power in kW?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-7/program.py b/root/organs10/physics/specialists/solved-power-7/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd0f7a09a6b943836f59e036efe84a95c50a782 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-7/program.py @@ -0,0 +1,7 @@ +"""power from power (Kilowatts and watts) +The maths organ (systems.py): solved from the system K = W; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(power): + return 0.001*power diff --git a/root/organs10/physics/specialists/solved-power-7/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-7/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-7/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-8/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-8/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-8/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-8/panel.json b/root/organs10/physics/specialists/solved-power-8/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f7473364a487773c3003cfbb10f64d1e02a9e324 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-8/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power in W for power 107.961?", + "a": "107960.66588996201", + "valid": true, + "kind": "compute", + "expect": 107960.66588996201, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [107.960666] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 107.961.", + "a": "107960.66588996201", + "valid": true, + "kind": "compute", + "expect": 107960.66588996201, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [107.960666] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W for power 22.652?", + "a": "22652.022796855792", + "valid": true, + "kind": "compute", + "expect": 22652.022796855792, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [22.652023] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 22.652.", + "a": "22652.022796855792", + "valid": true, + "kind": "compute", + "expect": 22652.022796855792, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [22.652023] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W for power 173.394?", + "a": "173393.6384053025", + "valid": true, + "kind": "compute", + "expect": 173393.6384053025, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [173.393638] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 173.394.", + "a": "173393.6384053025", + "valid": true, + "kind": "compute", + "expect": 173393.6384053025, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [173.393638] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W for power 126.709?", + "a": "126709.25180018238", + "valid": true, + "kind": "compute", + "expect": 126709.25180018238, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [126.709252] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 126.709.", + "a": "126709.25180018238", + "valid": true, + "kind": "compute", + "expect": 126709.25180018238, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [126.709252] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W for power 0.671697?", + "a": "671.6971997941935", + "valid": true, + "kind": "compute", + "expect": 671.6971997941935, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.671697] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 0.671697.", + "a": "671.6971997941935", + "valid": true, + "kind": "compute", + "expect": 671.6971997941935, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.671697] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W for power 1.16997?", + "a": "1169.9680059779357", + "valid": true, + "kind": "compute", + "expect": 1169.9680059779357, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [1.169968] (the system Kilowatts and watts)" + }, + { + "q": "Tell me the power in W with power of 1.16997.", + "a": "1169.9680059779357", + "valid": true, + "kind": "compute", + "expect": 1169.9680059779357, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [1.169968] (the system Kilowatts and watts)" + }, + { + "q": "What is the power in W?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the power in W, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the power in W of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power in W of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power in W with power of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which power in W is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the power is 2.57003, what is the power in W?", + "a": "2570.0299133036438", + "valid": true, + "kind": "compute", + "expect": 2570.0299133036438, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [2.57003] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 2.57003?", + "a": "2570.0299133036438", + "valid": true, + "kind": "compute", + "expect": 2570.0299133036438, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [2.57003] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in W for a power of 48.921, please.", + "a": "48920.990860011836", + "valid": true, + "kind": "compute", + "expect": 48920.990860011836, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [48.920991] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 48.921, what is the power in W?", + "a": "48920.990860011836", + "valid": true, + "kind": "compute", + "expect": 48920.990860011836, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [48.920991] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 0.348438?", + "a": "348.4376696300305", + "valid": true, + "kind": "compute", + "expect": 348.4376696300305, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.348438] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in W for a power of 0.348438, please.", + "a": "348.4376696300305", + "valid": true, + "kind": "compute", + "expect": 348.4376696300305, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [0.348438] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 252.709, what is the power in W?", + "a": "252709.02424952752", + "valid": true, + "kind": "compute", + "expect": 252709.02424952752, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [252.709024] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 252.709?", + "a": "252709.02424952752", + "valid": true, + "kind": "compute", + "expect": 252709.02424952752, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [252.709024] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in W for a power of 20.3966, please.", + "a": "20396.557961963437", + "valid": true, + "kind": "compute", + "expect": 20396.557961963437, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [20.396558] (the system Kilowatts and watts)" + }, + { + "q": "If the power is 20.3966, what is the power in W?", + "a": "20396.557961963437", + "valid": true, + "kind": "compute", + "expect": 20396.557961963437, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [20.396558] (the system Kilowatts and watts)" + }, + { + "q": "Could you work out the power in W given power = 134.993?", + "a": "134992.957580738", + "valid": true, + "kind": "compute", + "expect": 134992.957580738, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [134.992958] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in W for a power of 134.993, please.", + "a": "134992.957580738", + "valid": true, + "kind": "compute", + "expect": 134992.957580738, + "dtype": "quantity", + "unit": "W", + "why": "power in W for [134.992958] (the system Kilowatts and watts)" + }, + { + "q": "I need the power in W, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Can you tell me the power in W?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the power in W of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power in W of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power in W given power = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "What is a typical power in W?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-8/program.py b/root/organs10/physics/specialists/solved-power-8/program.py new file mode 100644 index 0000000000000000000000000000000000000000..56aa979ad14ba9a67120259a2409312647cde2b9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-8/program.py @@ -0,0 +1,7 @@ +"""power from power (Kilowatts and watts) +The maths organ (systems.py): solved from the system K = W; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(power): + return 1000.0*power diff --git a/root/organs10/physics/specialists/solved-power-8/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-8/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-8/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-9/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-9/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-9/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-9/panel.json b/root/organs10/physics/specialists/solved-power-9/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0a20c7b86e9aa9e5dbc80eedf0e27cb5b5ed639c --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-9/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for voltage 107.961 and resistance 59.4105?", + "a": "196.18594931702103", + "valid": true, + "kind": "compute", + "expect": 196.18594931702103, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 107.961 and resistance of 59.4105.", + "a": "196.18594931702103", + "valid": true, + "kind": "compute", + "expect": 196.18594931702103, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 169.527 and resistance 280.774?", + "a": "102.35783883502701", + "valid": true, + "kind": "compute", + "expect": 102.35783883502701, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 169.527 and resistance of 280.774.", + "a": "102.35783883502701", + "valid": true, + "kind": "compute", + "expect": 102.35783883502701, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 1.91195 and resistance 82.2401?", + "a": "0.044449858348614764", + "valid": true, + "kind": "compute", + "expect": 0.044449858348614764, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 1.91195 and resistance of 82.2401.", + "a": "0.044449858348614764", + "valid": true, + "kind": "compute", + "expect": 0.044449858348614764, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 1.64379 and resistance 252.709?", + "a": "0.010692390732604619", + "valid": true, + "kind": "compute", + "expect": 0.010692390732604619, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 1.64379 and resistance of 252.709.", + "a": "0.010692390732604619", + "valid": true, + "kind": "compute", + "expect": 0.010692390732604619, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 18.3169 and resistance 6.8386?", + "a": "49.060876880987344", + "valid": true, + "kind": "compute", + "expect": 49.060876880987344, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 18.3169 and resistance of 6.8386.", + "a": "49.060876880987344", + "valid": true, + "kind": "compute", + "expect": 49.060876880987344, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 156.502 and resistance 185.886?", + "a": "131.76237328638837", + "valid": true, + "kind": "compute", + "expect": 131.76237328638837, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Resistor power)" + }, + { + "q": "Tell me the power with voltage of 156.502 and resistance of 185.886.", + "a": "131.76237328638837", + "valid": true, + "kind": "compute", + "expect": 131.76237328638837, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Resistor power)" + }, + { + "q": "What is the power for voltage 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the resistance is not given" + }, + { + "q": "Tell me the power with voltage of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the resistance is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with voltage of -1.91195 and resistance of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the voltage is 8.50728 and the resistance is 17.7888, what is the power?", + "a": "4.068512049389283", + "valid": true, + "kind": "compute", + "expect": 4.068512049389283, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Resistor power)" + }, + { + "q": "Could you work out the power given voltage = 8.50728, resistance = 17.7888?", + "a": "4.068512049389283", + "valid": true, + "kind": "compute", + "expect": 4.068512049389283, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Resistor power)" + }, + { + "q": "I need the power for a voltage of 8.24951 and a resistance of 0.634021, please.", + "a": "107.33779475702875", + "valid": true, + "kind": "compute", + "expect": 107.33779475702875, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Resistor power)" + }, + { + "q": "If the voltage is 8.24951 and the resistance is 0.634021, what is the power?", + "a": "107.33779475702875", + "valid": true, + "kind": "compute", + "expect": 107.33779475702875, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Resistor power)" + }, + { + "q": "Could you work out the power given voltage = 0.318734, resistance = 9.56607?", + "a": "0.010619970649664055", + "valid": true, + "kind": "compute", + "expect": 0.010619970649664055, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Resistor power)" + }, + { + "q": "I need the power for a voltage of 0.318734 and a resistance of 9.56607, please.", + "a": "0.010619970649664055", + "valid": true, + "kind": "compute", + "expect": 0.010619970649664055, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Resistor power)" + }, + { + "q": "If the voltage is 0.671697 and the resistance is 14.2496, what is the power?", + "a": "0.031662509806997814", + "valid": true, + "kind": "compute", + "expect": 0.031662509806997814, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Resistor power)" + }, + { + "q": "Could you work out the power given voltage = 0.671697, resistance = 14.2496?", + "a": "0.031662509806997814", + "valid": true, + "kind": "compute", + "expect": 0.031662509806997814, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Resistor power)" + }, + { + "q": "I need the power for a voltage of 21.7931 and a resistance of 29.5106, please.", + "a": "16.093885686410946", + "valid": true, + "kind": "compute", + "expect": 16.093885686410946, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Resistor power)" + }, + { + "q": "If the voltage is 21.7931 and the resistance is 29.5106, what is the power?", + "a": "16.093885686410946", + "valid": true, + "kind": "compute", + "expect": 16.093885686410946, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Resistor power)" + }, + { + "q": "Could you work out the power given voltage = 153.15, resistance = 18.5953?", + "a": "1261.3344397561323", + "valid": true, + "kind": "compute", + "expect": 1261.3344397561323, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Resistor power)" + }, + { + "q": "I need the power for a voltage of 153.15 and a resistance of 18.5953, please.", + "a": "1261.3344397561323", + "valid": true, + "kind": "compute", + "expect": 1261.3344397561323, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Resistor power)" + }, + { + "q": "If the voltage is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the resistance is not given" + }, + { + "q": "Could you work out the power given voltage = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the resistance is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given voltage = -0.318734, resistance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-9/program.py b/root/organs10/physics/specialists/solved-power-9/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6868307b37c33aab3af27258f43af17169749747 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-9/program.py @@ -0,0 +1,7 @@ +"""power from voltage, resistance (Resistor power) +The maths organ (systems.py): solved from the system P = U**2/R; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(voltage, resistance): + return 1.0*voltage**2/resistance diff --git a/root/organs10/physics/specialists/solved-power-9/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-9/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-9/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power-efficiency/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power-efficiency/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-efficiency/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power-efficiency/panel.json b/root/organs10/physics/specialists/solved-power-efficiency/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..49129077c78f6841a13247faf3c8de7169ed35dd --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-efficiency/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power efficiency for output power 107.961 and input power 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [107.960666, 59.4105] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 107.961 and input power of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [107.960666, 59.4105] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 169.527 and input power 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [169.526958, 280.773702] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 169.527 and input power of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [169.526958, 280.773702] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 1.91195 and input power 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [1.911952, 82.240072] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 1.91195 and input power of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [1.911952, 82.240072] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 1.64379 and input power 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [1.643795, 252.709024] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 1.64379 and input power of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [1.643795, 252.709024] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 18.3169 and input power 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [18.316867, 6.838598] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 18.3169 and input power of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [18.316867, 6.838598] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 156.502 and input power 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [156.50181, 185.886273] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the power efficiency with output power of 156.502 and input power of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [156.50181, 185.886273] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the power efficiency for output power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "Tell me the power efficiency with output power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "What is the power efficiency of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power efficiency of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power efficiency with output power of -1.91195 and input power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative output power: no example had one" + }, + { + "q": "Which power efficiency is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the output power is 8.50728 and the input power is 17.7888, what is the power efficiency?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [8.507283, 17.788778] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the power efficiency given output power = 8.50728, input power = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [8.507283, 17.788778] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the power efficiency for an output power of 8.24951 and an input power of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [8.24951, 0.634021] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the output power is 8.24951 and the input power is 0.634021, what is the power efficiency?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [8.24951, 0.634021] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the power efficiency given output power = 0.318734, input power = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [0.318734, 9.566071] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the power efficiency for an output power of 0.318734 and an input power of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [0.318734, 9.566071] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the output power is 0.671697 and the input power is 14.2496, what is the power efficiency?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [0.671697, 14.249569] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the power efficiency given output power = 0.671697, input power = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [0.671697, 14.249569] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the power efficiency for an output power of 21.7931 and an input power of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [21.793126, 29.510609] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the output power is 21.7931 and the input power is 29.5106, what is the power efficiency?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [21.793126, 29.510609] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the power efficiency given output power = 153.15, input power = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [153.149965, 18.595315] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the power efficiency for an output power of 153.15 and an input power of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "power efficiency for [153.149965, 18.595315] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the output power is 8.50728, what is the power efficiency?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "Could you work out the power efficiency given output power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "Do you know the power efficiency of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power efficiency of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power efficiency given output power = -0.318734, input power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative output power: no example had one" + }, + { + "q": "What is a typical power efficiency?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power-efficiency/program.py b/root/organs10/physics/specialists/solved-power-efficiency/program.py new file mode 100644 index 0000000000000000000000000000000000000000..7e16b35bf1655302c22b81340d4673397a847eb7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-efficiency/program.py @@ -0,0 +1,7 @@ +"""power efficiency from output power, input power (power efficiency (Wikidata Q11945244)) +The maths organ (systems.py): solved from the system q2 = ((q0)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(output_power, input_power): + return 1.0*output_power/input_power diff --git a/root/organs10/physics/specialists/solved-power-efficiency/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power-efficiency/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power-efficiency/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-power/panel.json b/root/organs10/physics/specialists/solved-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..4558ce56f9852f4ce7ae6edc92b7fedc2430a0d4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the power for energy 107.961 and time 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 107.961 and time of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "W", + "why": "power for [107.960666, 59.4105] (the system Power from energy)" + }, + { + "q": "What is the power for energy 169.527 and time 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 169.527 and time of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "W", + "why": "power for [169.526958, 280.773702] (the system Power from energy)" + }, + { + "q": "What is the power for energy 1.91195 and time 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 1.91195 and time of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.911952, 82.240072] (the system Power from energy)" + }, + { + "q": "What is the power for energy 1.64379 and time 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 1.64379 and time of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "W", + "why": "power for [1.643795, 252.709024] (the system Power from energy)" + }, + { + "q": "What is the power for energy 18.3169 and time 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 18.3169 and time of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "W", + "why": "power for [18.316867, 6.838598] (the system Power from energy)" + }, + { + "q": "What is the power for energy 156.502 and time 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Power from energy)" + }, + { + "q": "Tell me the power with energy of 156.502 and time of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "W", + "why": "power for [156.50181, 185.886273] (the system Power from energy)" + }, + { + "q": "What is the power for energy 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Tell me the power with energy of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "What is the power of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the power of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the power with energy of -1.91195 and time of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative energy: no example had one" + }, + { + "q": "Which power is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the energy is 8.50728 and the time is 17.7888, what is the power?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Power from energy)" + }, + { + "q": "Could you work out the power given energy = 8.50728, time = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.507283, 17.788778] (the system Power from energy)" + }, + { + "q": "I need the power for an energy of 8.24951 and a time of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Power from energy)" + }, + { + "q": "If the energy is 8.24951 and the time is 0.634021, what is the power?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "W", + "why": "power for [8.24951, 0.634021] (the system Power from energy)" + }, + { + "q": "Could you work out the power given energy = 0.318734, time = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Power from energy)" + }, + { + "q": "I need the power for an energy of 0.318734 and a time of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.318734, 9.566071] (the system Power from energy)" + }, + { + "q": "If the energy is 0.671697 and the time is 14.2496, what is the power?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Power from energy)" + }, + { + "q": "Could you work out the power given energy = 0.671697, time = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "W", + "why": "power for [0.671697, 14.249569] (the system Power from energy)" + }, + { + "q": "I need the power for an energy of 21.7931 and a time of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Power from energy)" + }, + { + "q": "If the energy is 21.7931 and the time is 29.5106, what is the power?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "W", + "why": "power for [21.793126, 29.510609] (the system Power from energy)" + }, + { + "q": "Could you work out the power given energy = 153.15, time = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Power from energy)" + }, + { + "q": "I need the power for an energy of 153.15 and a time of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "W", + "why": "power for [153.149965, 18.595315] (the system Power from energy)" + }, + { + "q": "If the energy is 8.50728, what is the power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Could you work out the power given energy = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Do you know the power of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the power of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the power given energy = -0.318734, time = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative energy: no example had one" + }, + { + "q": "What is a typical power?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-power/program.py b/root/organs10/physics/specialists/solved-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0a399f4a4ae2e98dc04e0aaac6b8e4afab7b1d --- /dev/null +++ b/root/organs10/physics/specialists/solved-power/program.py @@ -0,0 +1,7 @@ +"""power from energy, time (Power from energy) +The maths organ (systems.py): solved from the system P = E/t; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(energy, time): + return 1.0*energy/time diff --git a/root/organs10/physics/specialists/solved-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-power/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-poynting-vector/organ_formula_v2.py b/root/organs10/physics/specialists/solved-poynting-vector/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poynting-vector/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-poynting-vector/panel.json b/root/organs10/physics/specialists/solved-poynting-vector/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c0ee6dafc9d7fdb9aa2ecfdab96ffc8cfbfbf0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poynting-vector/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Poynting vector for electric field strength 107.961 and magnetic field strength 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [107.960666, 59.4105] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 107.961 and magnetic field strength of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [107.960666, 59.4105] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 169.527 and magnetic field strength 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [169.526958, 280.773702] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 169.527 and magnetic field strength of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [169.526958, 280.773702] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 1.91195 and magnetic field strength 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [1.911952, 82.240072] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 1.91195 and magnetic field strength of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [1.911952, 82.240072] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 1.64379 and magnetic field strength 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [1.643795, 252.709024] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 1.64379 and magnetic field strength of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [1.643795, 252.709024] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 18.3169 and magnetic field strength 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [18.316867, 6.838598] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 18.3169 and magnetic field strength of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [18.316867, 6.838598] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 156.502 and magnetic field strength 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [156.50181, 185.886273] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 156.502 and magnetic field strength of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [156.50181, 185.886273] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "What is the Poynting vector for electric field strength 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic field strength is not given" + }, + { + "q": "Tell me the Poynting vector with electric field strength of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic field strength is not given" + }, + { + "q": "What is the Poynting vector of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Poynting vector of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Poynting vector with electric field strength of -1.91195 and magnetic field strength of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative electric field strength: no example had one" + }, + { + "q": "Which Poynting vector is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the electric field strength is 8.50728 and the magnetic field strength is 17.7888, what is the Poynting vector?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [8.507283, 17.788778] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = 8.50728, magnetic field strength = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [8.507283, 17.788778] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "I need the Poynting vector for an electric field strength of 8.24951 and a magnetic field strength of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [8.24951, 0.634021] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "If the electric field strength is 8.24951 and the magnetic field strength is 0.634021, what is the Poynting vector?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [8.24951, 0.634021] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = 0.318734, magnetic field strength = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [0.318734, 9.566071] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "I need the Poynting vector for an electric field strength of 0.318734 and a magnetic field strength of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [0.318734, 9.566071] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "If the electric field strength is 0.671697 and the magnetic field strength is 14.2496, what is the Poynting vector?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [0.671697, 14.249569] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = 0.671697, magnetic field strength = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [0.671697, 14.249569] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "I need the Poynting vector for an electric field strength of 21.7931 and a magnetic field strength of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [21.793126, 29.510609] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "If the electric field strength is 21.7931 and the magnetic field strength is 29.5106, what is the Poynting vector?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [21.793126, 29.510609] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = 153.15, magnetic field strength = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [153.149965, 18.595315] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "I need the Poynting vector for an electric field strength of 153.15 and a magnetic field strength of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "Poynting vector for [153.149965, 18.595315] (the system Poynting vector (Wikidata Q504186))" + }, + { + "q": "If the electric field strength is 8.50728, what is the Poynting vector?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic field strength is not given" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic field strength is not given" + }, + { + "q": "Do you know the Poynting vector of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Poynting vector of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Poynting vector given electric field strength = -0.318734, magnetic field strength = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative electric field strength: no example had one" + }, + { + "q": "What is a typical Poynting vector?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-poynting-vector/program.py b/root/organs10/physics/specialists/solved-poynting-vector/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0440d130396479ae19bdeed7d80fba7d243fe076 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poynting-vector/program.py @@ -0,0 +1,7 @@ +"""Poynting vector from electric field strength, magnetic field strength (Poynting vector (Wikidata Q504186)) +The maths organ (systems.py): solved from the system q1 = q2 * q3; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(electric_field_strength, magnetic_field_strength): + return 1.0*electric_field_strength*magnetic_field_strength diff --git a/root/organs10/physics/specialists/solved-poynting-vector/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-poynting-vector/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-poynting-vector/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-prandtl-number/organ_formula_v2.py b/root/organs10/physics/specialists/solved-prandtl-number/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-prandtl-number/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-prandtl-number/panel.json b/root/organs10/physics/specialists/solved-prandtl-number/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6b8c84e4275e6cc44034f1ced0bba166d5061712 --- /dev/null +++ b/root/organs10/physics/specialists/solved-prandtl-number/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Prandtl number for kinematic viscosity 107.961 and thermal diffusivity 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [107.960666, 59.4105] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 107.961 and thermal diffusivity of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [107.960666, 59.4105] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 169.527 and thermal diffusivity 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [169.526958, 280.773702] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 169.527 and thermal diffusivity of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [169.526958, 280.773702] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 1.91195 and thermal diffusivity 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [1.911952, 82.240072] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 1.91195 and thermal diffusivity of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [1.911952, 82.240072] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 1.64379 and thermal diffusivity 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [1.643795, 252.709024] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 1.64379 and thermal diffusivity of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [1.643795, 252.709024] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 18.3169 and thermal diffusivity 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [18.316867, 6.838598] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 18.3169 and thermal diffusivity of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [18.316867, 6.838598] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 156.502 and thermal diffusivity 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [156.50181, 185.886273] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 156.502 and thermal diffusivity of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [156.50181, 185.886273] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "What is the Prandtl number for kinematic viscosity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "What is the Prandtl number of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Prandtl number of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Prandtl number with kinematic viscosity of -1.91195 and thermal diffusivity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative kinematic viscosity: no example had one" + }, + { + "q": "Which Prandtl number is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the kinematic viscosity is 8.50728 and the thermal diffusivity is 17.7888, what is the Prandtl number?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [8.507283, 17.788778] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = 8.50728, thermal diffusivity = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [8.507283, 17.788778] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "I need the Prandtl number for a kinematic viscosity of 8.24951 and a thermal diffusivity of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [8.24951, 0.634021] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "If the kinematic viscosity is 8.24951 and the thermal diffusivity is 0.634021, what is the Prandtl number?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [8.24951, 0.634021] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = 0.318734, thermal diffusivity = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [0.318734, 9.566071] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "I need the Prandtl number for a kinematic viscosity of 0.318734 and a thermal diffusivity of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [0.318734, 9.566071] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "If the kinematic viscosity is 0.671697 and the thermal diffusivity is 14.2496, what is the Prandtl number?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [0.671697, 14.249569] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = 0.671697, thermal diffusivity = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [0.671697, 14.249569] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "I need the Prandtl number for a kinematic viscosity of 21.7931 and a thermal diffusivity of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [21.793126, 29.510609] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "If the kinematic viscosity is 21.7931 and the thermal diffusivity is 29.5106, what is the Prandtl number?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [21.793126, 29.510609] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = 153.15, thermal diffusivity = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [153.149965, 18.595315] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "I need the Prandtl number for a kinematic viscosity of 153.15 and a thermal diffusivity of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "Prandtl number for [153.149965, 18.595315] (the system Prandtl number (Wikidata Q815306))" + }, + { + "q": "If the kinematic viscosity is 8.50728, what is the Prandtl number?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Do you know the Prandtl number of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Prandtl number of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Prandtl number given kinematic viscosity = -0.318734, thermal diffusivity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative kinematic viscosity: no example had one" + }, + { + "q": "What is a typical Prandtl number?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-prandtl-number/program.py b/root/organs10/physics/specialists/solved-prandtl-number/program.py new file mode 100644 index 0000000000000000000000000000000000000000..92b7a7431298d05022a4b7d920954fbaf46faa37 --- /dev/null +++ b/root/organs10/physics/specialists/solved-prandtl-number/program.py @@ -0,0 +1,7 @@ +"""Prandtl number from kinematic viscosity, thermal diffusivity (Prandtl number (Wikidata Q815306)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(kinematic_viscosity, thermal_diffusivity): + return 1.0*kinematic_viscosity/thermal_diffusivity diff --git a/root/organs10/physics/specialists/solved-prandtl-number/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-prandtl-number/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-prandtl-number/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-2/panel.json b/root/organs10/physics/specialists/solved-pressure-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..340f5e5d0a875af89ef31dd51b3c29bddf0b8b03 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for volume 107.961, amount 59.4105 and temperature 5.77717?", + "a": "26.433007658639784", + "valid": true, + "kind": "compute", + "expect": 26.433007658639784, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 107.961, amount of 59.4105 and temperature of 5.77717.", + "a": "26.433007658639784", + "valid": true, + "kind": "compute", + "expect": 26.433007658639784, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 85.2416, amount 160.878 and temperature 2.69428?", + "a": "42.27883739437229", + "valid": true, + "kind": "compute", + "expect": 42.27883739437229, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 85.2416, amount of 160.878 and temperature of 2.69428.", + "a": "42.27883739437229", + "valid": true, + "kind": "compute", + "expect": 42.27883739437229, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 45.6157, amount 4.97131 and temperature 94.305?", + "a": "85.45267924819802", + "valid": true, + "kind": "compute", + "expect": 85.45267924819802, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 45.6157, amount of 4.97131 and temperature of 94.305.", + "a": "85.45267924819802", + "valid": true, + "kind": "compute", + "expect": 85.45267924819802, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 10.5638, amount 198.839 and temperature 0.671697?", + "a": "105.12046370446184", + "valid": true, + "kind": "compute", + "expect": 105.12046370446184, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 10.5638, amount of 198.839 and temperature of 0.671697.", + "a": "105.12046370446184", + "valid": true, + "kind": "compute", + "expect": 105.12046370446184, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 21.7931, amount 29.5106 and temperature 8.50341?", + "a": "95.73831694915789", + "valid": true, + "kind": "compute", + "expect": 95.73831694915789, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 21.7931, amount of 29.5106 and temperature of 8.50341.", + "a": "95.73831694915789", + "valid": true, + "kind": "compute", + "expect": 95.73831694915789, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 223.509, amount 17.3414 and temperature 7.10705?", + "a": "4.584731613380552", + "valid": true, + "kind": "compute", + "expect": 4.584731613380552, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system Ideal gas)" + }, + { + "q": "Tell me the pressure with volume of 223.509, amount of 17.3414 and temperature of 7.10705.", + "a": "4.584731613380552", + "valid": true, + "kind": "compute", + "expect": 4.584731613380552, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system Ideal gas)" + }, + { + "q": "What is the pressure for volume 107.961 and amount 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature is not given" + }, + { + "q": "Tell me the pressure with volume of 85.2416 and amount of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with volume of -45.6157, amount of 4.97131 and temperature of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume is 17.7888, amount is 167.625 and the temperature is 10.3291, what is the pressure?", + "a": "809.2585373474978", + "valid": true, + "kind": "compute", + "expect": 809.2585373474978, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system Ideal gas)" + }, + { + "q": "Could you work out the pressure given volume = 17.7888, amount = 167.625, temperature = 10.3291?", + "a": "809.2585373474978", + "valid": true, + "kind": "compute", + "expect": 809.2585373474978, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system Ideal gas)" + }, + { + "q": "I need the pressure for a volume of 21.511, an amount of 173.394 and a temperature of 251.084, please.", + "a": "16827.729712497752", + "valid": true, + "kind": "compute", + "expect": 16827.729712497752, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system Ideal gas)" + }, + { + "q": "If the volume is 21.511, amount is 173.394 and the temperature is 251.084, what is the pressure?", + "a": "16827.729712497752", + "valid": true, + "kind": "compute", + "expect": 16827.729712497752, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system Ideal gas)" + }, + { + "q": "Could you work out the pressure given volume = 129.245, amount = 1.18359, temperature = 15.9416?", + "a": "1.21381915049748", + "valid": true, + "kind": "compute", + "expect": 1.21381915049748, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system Ideal gas)" + }, + { + "q": "I need the pressure for a volume of 129.245, an amount of 1.18359 and a temperature of 15.9416, please.", + "a": "1.21381915049748", + "valid": true, + "kind": "compute", + "expect": 1.21381915049748, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system Ideal gas)" + }, + { + "q": "If the volume is 20.3966, amount is 18.3169 and the temperature is 6.8386, what is the pressure?", + "a": "51.06173560432413", + "valid": true, + "kind": "compute", + "expect": 51.06173560432413, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system Ideal gas)" + }, + { + "q": "Could you work out the pressure given volume = 20.3966, amount = 18.3169, temperature = 6.8386?", + "a": "51.06173560432413", + "valid": true, + "kind": "compute", + "expect": 51.06173560432413, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system Ideal gas)" + }, + { + "q": "I need the pressure for a volume of 185.886, an amount of 13.2373 and a temperature of 4.71941, please.", + "a": "2.794311326583418", + "valid": true, + "kind": "compute", + "expect": 2.794311326583418, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system Ideal gas)" + }, + { + "q": "If the volume is 185.886, amount is 13.2373 and the temperature is 4.71941, what is the pressure?", + "a": "2.794311326583418", + "valid": true, + "kind": "compute", + "expect": 2.794311326583418, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system Ideal gas)" + }, + { + "q": "Could you work out the pressure given volume = 9.1061, amount = 24.5721, temperature = 108.451?", + "a": "2433.191705884186", + "valid": true, + "kind": "compute", + "expect": 2433.191705884186, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system Ideal gas)" + }, + { + "q": "I need the pressure for a volume of 9.1061, an amount of 24.5721 and a temperature of 108.451, please.", + "a": "2433.191705884186", + "valid": true, + "kind": "compute", + "expect": 2433.191705884186, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system Ideal gas)" + }, + { + "q": "If the volume is 17.7888 and the amount is 167.625, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature is not given" + }, + { + "q": "Could you work out the pressure given volume = 21.511, amount = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the temperature is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given volume = -129.245, amount = 1.18359, temperature = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-2/program.py b/root/organs10/physics/specialists/solved-pressure-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6c24bec500c9584ccb938c2e8b1edefd5369b04b --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-2/program.py @@ -0,0 +1,7 @@ +"""pressure from volume, amount, temperature (Ideal gas) +The maths organ (systems.py): solved from the system p*V = n*R*T; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume, amount, temperature): + return 8.314462618*amount*temperature/volume diff --git a/root/organs10/physics/specialists/solved-pressure-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-3/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-3/panel.json b/root/organs10/physics/specialists/solved-pressure-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5424d0758dca757c3aaa2477826f5b64e8443ce3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for enthalpy 107.961, internal energy 59.4105 and volume 5.77717?", + "a": "8.40380514310675", + "valid": true, + "kind": "compute", + "expect": 8.40380514310675, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 107.961, internal energy of 59.4105 and volume of 5.77717.", + "a": "8.40380514310675", + "valid": true, + "kind": "compute", + "expect": 8.40380514310675, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 82.2401, internal energy 13.999 and volume 0.348438?", + "a": "195.84863763437602", + "valid": true, + "kind": "compute", + "expect": 195.84863763437602, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [82.240072, 13.999029, 0.348438] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 82.2401, internal energy of 13.999 and volume of 0.348438.", + "a": "195.84863763437602", + "valid": true, + "kind": "compute", + "expect": 195.84863763437602, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [82.240072, 13.999029, 0.348438] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 6.98086, internal energy 0.551236 and volume 2.88512?", + "a": "2.2285456772212138", + "valid": true, + "kind": "compute", + "expect": 2.2285456772212138, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [6.980857, 0.551236, 2.88512] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 6.98086, internal energy of 0.551236 and volume of 2.88512.", + "a": "2.2285456772212138", + "valid": true, + "kind": "compute", + "expect": 2.2285456772212138, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [6.980857, 0.551236, 2.88512] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 2.34957, internal energy 1.16997 and volume 1.14865?", + "a": "1.026944917824565", + "valid": true, + "kind": "compute", + "expect": 1.026944917824565, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [2.349571, 1.169968, 1.148652] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 2.34957, internal energy of 1.16997 and volume of 1.14865.", + "a": "1.026944917824565", + "valid": true, + "kind": "compute", + "expect": 1.026944917824565, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [2.349571, 1.169968, 1.148652] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 223.509, internal energy 17.3414 and volume 7.10705?", + "a": "29.00885536137714", + "valid": true, + "kind": "compute", + "expect": 29.00885536137714, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 223.509, internal energy of 17.3414 and volume of 7.10705.", + "a": "29.00885536137714", + "valid": true, + "kind": "compute", + "expect": 29.00885536137714, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 16.8989, internal energy 4.71659 and volume 4.07774?", + "a": "2.9875167729276084", + "valid": true, + "kind": "compute", + "expect": 2.9875167729276084, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [16.898916, 4.716591, 4.077743] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Tell me the pressure with enthalpy of 16.8989, internal energy of 4.71659 and volume of 4.07774.", + "a": "2.9875167729276084", + "valid": true, + "kind": "compute", + "expect": 2.9875167729276084, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [16.898916, 4.716591, 4.077743] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "What is the pressure for enthalpy 107.961 and internal energy 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Tell me the pressure with enthalpy of 82.2401 and internal energy of 13.999.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with enthalpy of -6.98086, internal energy of 0.551236 and volume of 2.88512.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative enthalpy: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the enthalpy is 8.24951, internal energy is 0.634021 and the volume is 6.34623, what is the pressure?", + "a": "1.2000028646440837", + "valid": true, + "kind": "compute", + "expect": 1.2000028646440837, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021, 6.346226] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Could you work out the pressure given enthalpy = 8.24951, internal energy = 0.634021, volume = 6.34623?", + "a": "1.2000028646440837", + "valid": true, + "kind": "compute", + "expect": 1.2000028646440837, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021, 6.346226] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "I need the pressure for an enthalpy of 126.709, an internal energy of 1.70503 and a volume of 2.9896, please.", + "a": "41.81302463299672", + "valid": true, + "kind": "compute", + "expect": 41.81302463299672, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [126.709252, 1.705032, 2.9896] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "If the enthalpy is 126.709, internal energy is 1.70503 and the volume is 2.9896, what is the pressure?", + "a": "41.81302463299672", + "valid": true, + "kind": "compute", + "expect": 41.81302463299672, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [126.709252, 1.705032, 2.9896] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Could you work out the pressure given enthalpy = 87.781, internal energy = 13.2084, volume = 246.329?", + "a": "0.30273568538290435", + "valid": true, + "kind": "compute", + "expect": 0.30273568538290435, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [87.781013, 13.208419, 246.329053] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "I need the pressure for an enthalpy of 87.781, an internal energy of 13.2084 and a volume of 246.329, please.", + "a": "0.30273568538290435", + "valid": true, + "kind": "compute", + "expect": 0.30273568538290435, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [87.781013, 13.208419, 246.329053] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "If the enthalpy is 186.27, internal energy is 106.508 and the volume is 156.502, what is the pressure?", + "a": "0.5096582582601115", + "valid": true, + "kind": "compute", + "expect": 0.5096582582601115, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [186.270057, 106.507617, 156.50181] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Could you work out the pressure given enthalpy = 186.27, internal energy = 106.508, volume = 156.502?", + "a": "0.5096582582601115", + "valid": true, + "kind": "compute", + "expect": 0.5096582582601115, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [186.270057, 106.507617, 156.50181] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "I need the pressure for an enthalpy of 88.6624, an internal energy of 0.633611 and a volume of 0.869111, please.", + "a": "101.28591758436798", + "valid": true, + "kind": "compute", + "expect": 101.28591758436798, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [88.662361, 0.633611, 0.869111] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "If the enthalpy is 88.6624, internal energy is 0.633611 and the volume is 0.869111, what is the pressure?", + "a": "101.28591758436798", + "valid": true, + "kind": "compute", + "expect": 101.28591758436798, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [88.662361, 0.633611, 0.869111] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "Could you work out the pressure given enthalpy = 1.90441, internal energy = 1.45374, volume = 27.5916?", + "a": "0.01633332913840586", + "valid": true, + "kind": "compute", + "expect": 0.01633332913840586, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.904407, 1.453744, 27.591617] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "I need the pressure for an enthalpy of 1.90441, an internal energy of 1.45374 and a volume of 27.5916, please.", + "a": "0.01633332913840586", + "valid": true, + "kind": "compute", + "expect": 0.01633332913840586, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.904407, 1.453744, 27.591617] (the system enthalpy (Wikidata Q161064))" + }, + { + "q": "If the enthalpy is 8.24951 and the internal energy is 0.634021, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Could you work out the pressure given enthalpy = 126.709, internal energy = 1.70503?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given enthalpy = -87.781, internal energy = 13.2084, volume = 246.329?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative enthalpy: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-3/program.py b/root/organs10/physics/specialists/solved-pressure-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc91e3efd93264965ec4610e5b6b45fc4ca9825 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-3/program.py @@ -0,0 +1,7 @@ +"""pressure from enthalpy, internal energy, volume (enthalpy (Wikidata Q161064)) +The maths organ (systems.py): solved from the system q0 = q1 + q2*q3; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(enthalpy, internal_energy, volume): + return (1.0*enthalpy - 1.0*internal_energy)/volume diff --git a/root/organs10/physics/specialists/solved-pressure-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-3/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-4/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-4/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-4/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-4/panel.json b/root/organs10/physics/specialists/solved-pressure-4/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..33859e1da548fefa0e5b1212379f594b2118be97 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-4/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for ambient pressure 107.961 and positive pressure 59.4105?", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 107.961 and positive pressure of 59.4105.", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 169.527 and positive pressure 280.774?", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 169.527 and positive pressure of 280.774.", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 1.91195 and positive pressure 82.2401?", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 1.91195 and positive pressure of 82.2401.", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 1.64379 and positive pressure 252.709?", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 1.64379 and positive pressure of 252.709.", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 18.3169 and positive pressure 6.8386?", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 18.3169 and positive pressure of 6.8386.", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 156.502 and positive pressure 185.886?", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Tell me the pressure with ambient pressure of 156.502 and positive pressure of 185.886.", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "What is the pressure for ambient pressure 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the positive pressure is not given" + }, + { + "q": "Tell me the pressure with ambient pressure of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the positive pressure is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with ambient pressure of -1.91195 and positive pressure of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative ambient pressure: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the ambient pressure is 8.50728 and the positive pressure is 17.7888, what is the pressure?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the pressure given ambient pressure = 8.50728, positive pressure = 17.7888?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the pressure for an ambient pressure of 8.24951 and a positive pressure of 0.634021, please.", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 8.24951 and the positive pressure is 0.634021, what is the pressure?", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the pressure given ambient pressure = 0.318734, positive pressure = 9.56607?", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the pressure for an ambient pressure of 0.318734 and a positive pressure of 9.56607, please.", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 0.671697 and the positive pressure is 14.2496, what is the pressure?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the pressure given ambient pressure = 0.671697, positive pressure = 14.2496?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the pressure for an ambient pressure of 21.7931 and a positive pressure of 29.5106, please.", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 21.7931 and the positive pressure is 29.5106, what is the pressure?", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "Could you work out the pressure given ambient pressure = 153.15, positive pressure = 18.5953?", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "I need the pressure for an ambient pressure of 153.15 and a positive pressure of 18.5953, please.", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system positive pressure (Wikidata Q331466))" + }, + { + "q": "If the ambient pressure is 8.50728, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the positive pressure is not given" + }, + { + "q": "Could you work out the pressure given ambient pressure = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the positive pressure is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given ambient pressure = -0.318734, positive pressure = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative ambient pressure: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-4/program.py b/root/organs10/physics/specialists/solved-pressure-4/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9ed208126ceca680a4b91bc219bd1d47ba5e47 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-4/program.py @@ -0,0 +1,7 @@ +"""pressure from ambient pressure, positive pressure (positive pressure (Wikidata Q331466)) +The maths organ (systems.py): solved from the system q1 = q2 - q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(ambient_pressure, positive_pressure): + return 1.0*ambient_pressure + 1.0*positive_pressure diff --git a/root/organs10/physics/specialists/solved-pressure-4/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-4/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-4/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-5/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-5/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-5/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-5/panel.json b/root/organs10/physics/specialists/solved-pressure-5/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5101417203f1e6d1e759593f8ed4f19fefec584f --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-5/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for magnetic pressure number 107.961, magnetic permeability 59.4105 and magnetic flux density 5.77717?", + "a": "30.32507160910141", + "valid": true, + "kind": "compute", + "expect": 30.32507160910141, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 107.961, magnetic permeability of 59.4105 and magnetic flux density of 5.77717.", + "a": "30.32507160910141", + "valid": true, + "kind": "compute", + "expect": 30.32507160910141, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 85.2416, magnetic permeability 160.878 and magnetic flux density 2.69428?", + "a": "1.9231328083280346", + "valid": true, + "kind": "compute", + "expect": 1.9231328083280346, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 85.2416, magnetic permeability of 160.878 and magnetic flux density of 2.69428.", + "a": "1.9231328083280346", + "valid": true, + "kind": "compute", + "expect": 1.9231328083280346, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 45.6157, magnetic permeability 4.97131 and magnetic flux density 94.305?", + "a": "40802.173643709364", + "valid": true, + "kind": "compute", + "expect": 40802.173643709364, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 45.6157, magnetic permeability of 4.97131 and magnetic flux density of 94.305.", + "a": "40802.173643709364", + "valid": true, + "kind": "compute", + "expect": 40802.173643709364, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 10.5638, magnetic permeability 198.839 and magnetic flux density 0.671697?", + "a": "0.011984986103356994", + "valid": true, + "kind": "compute", + "expect": 0.011984986103356994, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 10.5638, magnetic permeability of 198.839 and magnetic flux density of 0.671697.", + "a": "0.011984986103356994", + "valid": true, + "kind": "compute", + "expect": 0.011984986103356994, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 21.7931, magnetic permeability 29.5106 and magnetic flux density 8.50341?", + "a": "26.699143467388478", + "valid": true, + "kind": "compute", + "expect": 26.699143467388478, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 21.7931, magnetic permeability of 29.5106 and magnetic flux density of 8.50341.", + "a": "26.699143467388478", + "valid": true, + "kind": "compute", + "expect": 26.699143467388478, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 223.509, magnetic permeability 17.3414 and magnetic flux density 7.10705?", + "a": "325.5054253726801", + "valid": true, + "kind": "compute", + "expect": 325.5054253726801, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 223.509, magnetic permeability of 17.3414 and magnetic flux density of 7.10705.", + "a": "325.5054253726801", + "valid": true, + "kind": "compute", + "expect": 325.5054253726801, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "What is the pressure for magnetic pressure number 107.961 and magnetic permeability 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic flux density is not given" + }, + { + "q": "Tell me the pressure with magnetic pressure number of 85.2416 and magnetic permeability of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic flux density is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with magnetic pressure number of -45.6157, magnetic permeability of 4.97131 and magnetic flux density of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic pressure number: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the magnetic pressure number is 17.7888, magnetic permeability is 167.625 and the magnetic flux density is 10.3291, what is the pressure?", + "a": "5.661071003489753", + "valid": true, + "kind": "compute", + "expect": 5.661071003489753, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = 17.7888, magnetic permeability = 167.625, magnetic flux density = 10.3291?", + "a": "5.661071003489753", + "valid": true, + "kind": "compute", + "expect": 5.661071003489753, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "I need the pressure for a magnetic pressure number of 21.511, a magnetic permeability of 173.394 and a magnetic flux density of 251.084, please.", + "a": "3910.5331480078466", + "valid": true, + "kind": "compute", + "expect": 3910.5331480078466, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "If the magnetic pressure number is 21.511, magnetic permeability is 173.394 and the magnetic flux density is 251.084, what is the pressure?", + "a": "3910.5331480078466", + "valid": true, + "kind": "compute", + "expect": 3910.5331480078466, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = 129.245, magnetic permeability = 1.18359, magnetic flux density = 15.9416?", + "a": "13875.443389225476", + "valid": true, + "kind": "compute", + "expect": 13875.443389225476, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "I need the pressure for a magnetic pressure number of 129.245, a magnetic permeability of 1.18359 and a magnetic flux density of 15.9416, please.", + "a": "13875.443389225476", + "valid": true, + "kind": "compute", + "expect": 13875.443389225476, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "If the magnetic pressure number is 20.3966, magnetic permeability is 18.3169 and the magnetic flux density is 6.8386, what is the pressure?", + "a": "26.03813374028582", + "valid": true, + "kind": "compute", + "expect": 26.03813374028582, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = 20.3966, magnetic permeability = 18.3169, magnetic flux density = 6.8386?", + "a": "26.03813374028582", + "valid": true, + "kind": "compute", + "expect": 26.03813374028582, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "I need the pressure for a magnetic pressure number of 185.886, a magnetic permeability of 13.2373 and a magnetic flux density of 4.71941, please.", + "a": "156.38455201940317", + "valid": true, + "kind": "compute", + "expect": 156.38455201940317, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "If the magnetic pressure number is 185.886, magnetic permeability is 13.2373 and the magnetic flux density is 4.71941, what is the pressure?", + "a": "156.38455201940317", + "valid": true, + "kind": "compute", + "expect": 156.38455201940317, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = 9.1061, magnetic permeability = 24.5721, magnetic flux density = 108.451?", + "a": "2179.345284040078", + "valid": true, + "kind": "compute", + "expect": 2179.345284040078, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "I need the pressure for a magnetic pressure number of 9.1061, a magnetic permeability of 24.5721 and a magnetic flux density of 108.451, please.", + "a": "2179.345284040078", + "valid": true, + "kind": "compute", + "expect": 2179.345284040078, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system magnetic pressure number (Wikidata Q105102313))" + }, + { + "q": "If the magnetic pressure number is 17.7888 and the magnetic permeability is 167.625, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic flux density is not given" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = 21.511, magnetic permeability = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic flux density is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given magnetic pressure number = -129.245, magnetic permeability = 1.18359, magnetic flux density = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic pressure number: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-5/program.py b/root/organs10/physics/specialists/solved-pressure-5/program.py new file mode 100644 index 0000000000000000000000000000000000000000..54d33a145f21c10c5e763e9581cf5c868590d342 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-5/program.py @@ -0,0 +1,7 @@ +"""pressure from magnetic pressure number, magnetic permeability, magnetic flux density (magnetic pressure number (Wikidata Q105102313)) +The maths organ (systems.py): solved from the system q0 = ((2*q1*q2)/(q3 **(2))); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(magnetic_pressure_number, magnetic_permeability, magnetic_flux_density): + return 0.5*magnetic_flux_density**2*magnetic_pressure_number/magnetic_permeability diff --git a/root/organs10/physics/specialists/solved-pressure-5/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-5/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-5/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-6/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-6/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-6/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-6/panel.json b/root/organs10/physics/specialists/solved-pressure-6/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ec97db27f5b36598ffb8ed2540223b56976a8e58 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-6/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for partial pressure 107.961 and amount-of-substance fraction 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 107.961 and amount-of-substance fraction of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 169.527 and amount-of-substance fraction 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 169.527 and amount-of-substance fraction of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 1.91195 and amount-of-substance fraction 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 1.91195 and amount-of-substance fraction of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 1.64379 and amount-of-substance fraction 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 1.64379 and amount-of-substance fraction of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 18.3169 and amount-of-substance fraction 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 18.3169 and amount-of-substance fraction of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 156.502 and amount-of-substance fraction 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the pressure with partial pressure of 156.502 and amount-of-substance fraction of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the pressure for partial pressure 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance fraction is not given" + }, + { + "q": "Tell me the pressure with partial pressure of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance fraction is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with partial pressure of -1.91195 and amount-of-substance fraction of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative partial pressure: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the partial pressure is 8.50728 and the amount-of-substance fraction is 17.7888, what is the pressure?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the pressure given partial pressure = 8.50728, amount-of-substance fraction = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the pressure for a partial pressure of 8.24951 and an amount-of-substance fraction of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the partial pressure is 8.24951 and the amount-of-substance fraction is 0.634021, what is the pressure?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the pressure given partial pressure = 0.318734, amount-of-substance fraction = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the pressure for a partial pressure of 0.318734 and an amount-of-substance fraction of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the partial pressure is 0.671697 and the amount-of-substance fraction is 14.2496, what is the pressure?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the pressure given partial pressure = 0.671697, amount-of-substance fraction = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the pressure for a partial pressure of 21.7931 and an amount-of-substance fraction of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the partial pressure is 21.7931 and the amount-of-substance fraction is 29.5106, what is the pressure?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the pressure given partial pressure = 153.15, amount-of-substance fraction = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the pressure for a partial pressure of 153.15 and an amount-of-substance fraction of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the partial pressure is 8.50728, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance fraction is not given" + }, + { + "q": "Could you work out the pressure given partial pressure = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance fraction is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given partial pressure = -0.318734, amount-of-substance fraction = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative partial pressure: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-6/program.py b/root/organs10/physics/specialists/solved-pressure-6/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4004123ade306e184049f85379ad1adf2b28ca7b --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-6/program.py @@ -0,0 +1,7 @@ +"""pressure from partial pressure, amount-of-substance fraction (partial pressure (Wikidata Q27165)) +The maths organ (systems.py): solved from the system q0 = q1*q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(partial_pressure, amount_of_substance_fraction): + return 1.0*partial_pressure/amount_of_substance_fraction diff --git a/root/organs10/physics/specialists/solved-pressure-6/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-6/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-6/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure-7/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure-7/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-7/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure-7/panel.json b/root/organs10/physics/specialists/solved-pressure-7/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b27c0c6a23c9f8dffe6a5d70d21c5c9740b2a3c7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-7/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for volume 107.961, amount of substance 59.4105 and thermodynamic temperature 5.77717?", + "a": "26.432998699766674", + "valid": true, + "kind": "compute", + "expect": 26.432998699766674, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 107.961, amount of substance of 59.4105 and thermodynamic temperature of 5.77717.", + "a": "26.432998699766674", + "valid": true, + "kind": "compute", + "expect": 26.432998699766674, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105, 5.777165] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 85.2416, amount of substance 160.878 and thermodynamic temperature 2.69428?", + "a": "42.278823064911776", + "valid": true, + "kind": "compute", + "expect": 42.278823064911776, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 85.2416, amount of substance of 160.878 and thermodynamic temperature of 2.69428.", + "a": "42.278823064911776", + "valid": true, + "kind": "compute", + "expect": 42.278823064911776, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [85.241623, 160.878442, 2.69428] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 45.6157, amount of substance 4.97131 and thermodynamic temperature 94.305?", + "a": "85.45265028593536", + "valid": true, + "kind": "compute", + "expect": 85.45265028593536, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 45.6157, amount of substance of 4.97131 and thermodynamic temperature of 94.305.", + "a": "85.45265028593536", + "valid": true, + "kind": "compute", + "expect": 85.45265028593536, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [45.61567, 4.971307, 94.305046] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 10.5638, amount of substance 198.839 and thermodynamic temperature 0.671697?", + "a": "105.12042807624623", + "valid": true, + "kind": "compute", + "expect": 105.12042807624623, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 10.5638, amount of substance of 198.839 and thermodynamic temperature of 0.671697.", + "a": "105.12042807624623", + "valid": true, + "kind": "compute", + "expect": 105.12042807624623, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [10.563843, 198.838955, 0.671697] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 21.7931, amount of substance 29.5106 and thermodynamic temperature 8.50341?", + "a": "95.7382845008098", + "valid": true, + "kind": "compute", + "expect": 95.7382845008098, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 21.7931, amount of substance of 29.5106 and thermodynamic temperature of 8.50341.", + "a": "95.7382845008098", + "valid": true, + "kind": "compute", + "expect": 95.7382845008098, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609, 8.503407] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 223.509, amount of substance 17.3414 and thermodynamic temperature 7.10705?", + "a": "4.584730059488943", + "valid": true, + "kind": "compute", + "expect": 4.584730059488943, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Tell me the pressure with volume of 223.509, amount of substance of 17.3414 and thermodynamic temperature of 7.10705.", + "a": "4.584730059488943", + "valid": true, + "kind": "compute", + "expect": 4.584730059488943, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [223.508796, 17.341435, 7.107049] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "What is the pressure for volume 107.961 and amount of substance 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Tell me the pressure with volume of 85.2416 and amount of substance of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with volume of -45.6157, amount of substance of 4.97131 and thermodynamic temperature of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume is 17.7888, amount of substance is 167.625 and the thermodynamic temperature is 10.3291, what is the pressure?", + "a": "809.2582630675278", + "valid": true, + "kind": "compute", + "expect": 809.2582630675278, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Could you work out the pressure given volume = 17.7888, amount of substance = 167.625, thermodynamic temperature = 10.3291?", + "a": "809.2582630675278", + "valid": true, + "kind": "compute", + "expect": 809.2582630675278, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [17.788778, 167.624948, 10.329054] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "I need the pressure for a volume of 21.511, an amount of substance of 173.394 and a thermodynamic temperature of 251.084, please.", + "a": "16827.724009117446", + "valid": true, + "kind": "compute", + "expect": 16827.724009117446, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "If the volume is 21.511, amount of substance is 173.394 and the thermodynamic temperature is 251.084, what is the pressure?", + "a": "16827.724009117446", + "valid": true, + "kind": "compute", + "expect": 16827.724009117446, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.511016, 173.393638, 251.084037] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Could you work out the pressure given volume = 129.245, amount of substance = 1.18359, thermodynamic temperature = 15.9416?", + "a": "1.2138187391007942", + "valid": true, + "kind": "compute", + "expect": 1.2138187391007942, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "I need the pressure for a volume of 129.245, an amount of substance of 1.18359 and a thermodynamic temperature of 15.9416, please.", + "a": "1.2138187391007942", + "valid": true, + "kind": "compute", + "expect": 1.2138187391007942, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [129.244984, 1.18359, 15.941612] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "If the volume is 20.3966, amount of substance is 18.3169 and the thermodynamic temperature is 6.8386, what is the pressure?", + "a": "51.06171829809791", + "valid": true, + "kind": "compute", + "expect": 51.06171829809791, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Could you work out the pressure given volume = 20.3966, amount of substance = 18.3169, thermodynamic temperature = 6.8386?", + "a": "51.06171829809791", + "valid": true, + "kind": "compute", + "expect": 51.06171829809791, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [20.396558, 18.316867, 6.838598] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "I need the pressure for a volume of 185.886, an amount of substance of 13.2373 and a thermodynamic temperature of 4.71941, please.", + "a": "2.7943103795144753", + "valid": true, + "kind": "compute", + "expect": 2.7943103795144753, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "If the volume is 185.886, amount of substance is 13.2373 and the thermodynamic temperature is 4.71941, what is the pressure?", + "a": "2.7943103795144753", + "valid": true, + "kind": "compute", + "expect": 2.7943103795144753, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [185.886273, 13.237311, 4.719415] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "Could you work out the pressure given volume = 9.1061, amount of substance = 24.5721, thermodynamic temperature = 108.451?", + "a": "2433.190881208612", + "valid": true, + "kind": "compute", + "expect": 2433.190881208612, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "I need the pressure for a volume of 9.1061, an amount of substance of 24.5721 and a thermodynamic temperature of 108.451, please.", + "a": "2433.190881208612", + "valid": true, + "kind": "compute", + "expect": 2433.190881208612, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [9.106104, 24.572086, 108.450792] (the system ideal gas law (Wikidata Q191785))" + }, + { + "q": "If the volume is 17.7888 and the amount of substance is 167.625, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Could you work out the pressure given volume = 21.511, amount of substance = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given volume = -129.245, amount of substance = 1.18359, thermodynamic temperature = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure-7/program.py b/root/organs10/physics/specialists/solved-pressure-7/program.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c4173569a88fd120da2313eedf5a9a4cf26837 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-7/program.py @@ -0,0 +1,7 @@ +"""pressure from volume, amount of substance, thermodynamic temperature (ideal gas law (Wikidata Q191785)) +The maths organ (systems.py): solved from the system q0*q1 = q2*q3*q4; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume, amount_of_substance, thermodynamic_temperature): + return 8.3144598*amount_of_substance*thermodynamic_temperature/volume diff --git a/root/organs10/physics/specialists/solved-pressure-7/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure-7/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure-7/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-pressure/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pressure/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-pressure/panel.json b/root/organs10/physics/specialists/solved-pressure/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..fafbdb29094edf8870eeac97f102d98ee3c578bb --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pressure for force 107.961 and area 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 107.961 and area of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [107.960666, 59.4105] (the system Pressure)" + }, + { + "q": "What is the pressure for force 169.527 and area 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 169.527 and area of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [169.526958, 280.773702] (the system Pressure)" + }, + { + "q": "What is the pressure for force 1.91195 and area 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 1.91195 and area of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.911952, 82.240072] (the system Pressure)" + }, + { + "q": "What is the pressure for force 1.64379 and area 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 1.64379 and area of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [1.643795, 252.709024] (the system Pressure)" + }, + { + "q": "What is the pressure for force 18.3169 and area 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 18.3169 and area of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [18.316867, 6.838598] (the system Pressure)" + }, + { + "q": "What is the pressure for force 156.502 and area 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system Pressure)" + }, + { + "q": "Tell me the pressure with force of 156.502 and area of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [156.50181, 185.886273] (the system Pressure)" + }, + { + "q": "What is the pressure for force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the pressure with force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the pressure of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the pressure of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the pressure with force of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative force: no example had one" + }, + { + "q": "Which pressure is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the force is 8.50728 and the area is 17.7888, what is the pressure?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system Pressure)" + }, + { + "q": "Could you work out the pressure given force = 8.50728, area = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.507283, 17.788778] (the system Pressure)" + }, + { + "q": "I need the pressure for a force of 8.24951 and an area of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system Pressure)" + }, + { + "q": "If the force is 8.24951 and the area is 0.634021, what is the pressure?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [8.24951, 0.634021] (the system Pressure)" + }, + { + "q": "Could you work out the pressure given force = 0.318734, area = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system Pressure)" + }, + { + "q": "I need the pressure for a force of 0.318734 and an area of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.318734, 9.566071] (the system Pressure)" + }, + { + "q": "If the force is 0.671697 and the area is 14.2496, what is the pressure?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system Pressure)" + }, + { + "q": "Could you work out the pressure given force = 0.671697, area = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [0.671697, 14.249569] (the system Pressure)" + }, + { + "q": "I need the pressure for a force of 21.7931 and an area of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system Pressure)" + }, + { + "q": "If the force is 21.7931 and the area is 29.5106, what is the pressure?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [21.793126, 29.510609] (the system Pressure)" + }, + { + "q": "Could you work out the pressure given force = 153.15, area = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system Pressure)" + }, + { + "q": "I need the pressure for a force of 153.15 and an area of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "Pa", + "why": "pressure for [153.149965, 18.595315] (the system Pressure)" + }, + { + "q": "If the force is 8.50728, what is the pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the pressure given force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the pressure of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the pressure of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the pressure given force = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative force: no example had one" + }, + { + "q": "What is a typical pressure?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-pressure/program.py b/root/organs10/physics/specialists/solved-pressure/program.py new file mode 100644 index 0000000000000000000000000000000000000000..23d8d21cea71f6941ee30da8fd47b77c0a6067cd --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure/program.py @@ -0,0 +1,7 @@ +"""pressure from force, area (Pressure) +The maths organ (systems.py): solved from the system p = F/A; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(force, area): + return 1.0*force/area diff --git a/root/organs10/physics/specialists/solved-pressure/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pressure/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pressure/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-price/organ_formula_v2.py b/root/organs10/physics/specialists/solved-price/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-price/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-price/panel.json b/root/organs10/physics/specialists/solved-price/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..226b67247b151ea2e4045cc9ab5231915edf99e7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-price/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the price for cost 107.961 and energy 59.4105?", + "a": "1.8171983999893249", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893249, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [107.960666, 59.4105] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 107.961 and energy of 59.4105.", + "a": "1.8171983999893249", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893249, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [107.960666, 59.4105] (the system Energy cost)" + }, + { + "q": "What is the price for cost 169.527 and energy 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [169.526958, 280.773702] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 169.527 and energy of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [169.526958, 280.773702] (the system Energy cost)" + }, + { + "q": "What is the price for cost 1.91195 and energy 82.2401?", + "a": "0.023248420388592407", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592407, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [1.911952, 82.240072] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 1.91195 and energy of 82.2401.", + "a": "0.023248420388592407", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592407, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [1.911952, 82.240072] (the system Energy cost)" + }, + { + "q": "What is the price for cost 1.64379 and energy 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [1.643795, 252.709024] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 1.64379 and energy of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [1.643795, 252.709024] (the system Energy cost)" + }, + { + "q": "What is the price for cost 18.3169 and energy 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [18.316867, 6.838598] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 18.3169 and energy of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [18.316867, 6.838598] (the system Energy cost)" + }, + { + "q": "What is the price for cost 156.502 and energy 185.886?", + "a": "0.8419223616111586", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111586, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [156.50181, 185.886273] (the system Energy cost)" + }, + { + "q": "Tell me the price with cost of 156.502 and energy of 185.886.", + "a": "0.8419223616111586", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111586, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [156.50181, 185.886273] (the system Energy cost)" + }, + { + "q": "What is the price for cost 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the energy is not given" + }, + { + "q": "Tell me the price with cost of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the energy is not given" + }, + { + "q": "What is the price of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the price of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the price with cost of -1.91195 and energy of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative cost: no example had one" + }, + { + "q": "Which price is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the cost is 8.50728 and the energy is 17.7888, what is the price?", + "a": "0.47823872966731146", + "valid": true, + "kind": "compute", + "expect": 0.47823872966731146, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [8.507283, 17.788778] (the system Energy cost)" + }, + { + "q": "Could you work out the price given cost = 8.50728, energy = 17.7888?", + "a": "0.47823872966731146", + "valid": true, + "kind": "compute", + "expect": 0.47823872966731146, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [8.507283, 17.788778] (the system Energy cost)" + }, + { + "q": "I need the price for a cost of 8.24951 and an energy of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [8.24951, 0.634021] (the system Energy cost)" + }, + { + "q": "If the cost is 8.24951 and the energy is 0.634021, what is the price?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [8.24951, 0.634021] (the system Energy cost)" + }, + { + "q": "Could you work out the price given cost = 0.318734, energy = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [0.318734, 9.566071] (the system Energy cost)" + }, + { + "q": "I need the price for a cost of 0.318734 and an energy of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [0.318734, 9.566071] (the system Energy cost)" + }, + { + "q": "If the cost is 0.671697 and the energy is 14.2496, what is the price?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [0.671697, 14.249569] (the system Energy cost)" + }, + { + "q": "Could you work out the price given cost = 0.671697, energy = 14.2496?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [0.671697, 14.249569] (the system Energy cost)" + }, + { + "q": "I need the price for a cost of 21.7931 and an energy of 29.5106, please.", + "a": "0.7384844800541928", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541928, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [21.793126, 29.510609] (the system Energy cost)" + }, + { + "q": "If the cost is 21.7931 and the energy is 29.5106, what is the price?", + "a": "0.7384844800541928", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541928, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [21.793126, 29.510609] (the system Energy cost)" + }, + { + "q": "Could you work out the price given cost = 153.15, energy = 18.5953?", + "a": "8.235943368499308", + "valid": true, + "kind": "compute", + "expect": 8.235943368499308, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [153.149965, 18.595315] (the system Energy cost)" + }, + { + "q": "I need the price for a cost of 153.15 and an energy of 18.5953, please.", + "a": "8.235943368499308", + "valid": true, + "kind": "compute", + "expect": 8.235943368499308, + "dtype": "quantity", + "unit": "$/kWh", + "why": "price for [153.149965, 18.595315] (the system Energy cost)" + }, + { + "q": "If the cost is 8.50728, what is the price?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the energy is not given" + }, + { + "q": "Could you work out the price given cost = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the energy is not given" + }, + { + "q": "Do you know the price of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the price of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the price given cost = -0.318734, energy = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative cost: no example had one" + }, + { + "q": "What is a typical price?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-price/program.py b/root/organs10/physics/specialists/solved-price/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e3c57513c9fce137701cbe971b5017e06db78b --- /dev/null +++ b/root/organs10/physics/specialists/solved-price/program.py @@ -0,0 +1,7 @@ +"""price from cost, energy (Energy cost) +The maths organ (systems.py): solved from the system C = E*p; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(cost, energy): + return 1.0*cost/energy diff --git a/root/organs10/physics/specialists/solved-price/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-price/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-price/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-principal/organ_formula_v2.py b/root/organs10/physics/specialists/solved-principal/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-principal/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-principal/panel.json b/root/organs10/physics/specialists/solved-principal/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..77363696bbd78c1ae49089810419e334706db347 --- /dev/null +++ b/root/organs10/physics/specialists/solved-principal/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the principal for interest 107.961, annual rate 59.4105 and time 5.77717?", + "a": "0.3145484889716048", + "valid": true, + "kind": "compute", + "expect": 0.3145484889716048, + "dtype": "quantity", + "unit": "$", + "why": "principal for [107.960666, 59.4105, 5.777165] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 107.961, annual rate of 59.4105 and time of 5.77717.", + "a": "0.3145484889716048", + "valid": true, + "kind": "compute", + "expect": 0.3145484889716048, + "dtype": "quantity", + "unit": "$", + "why": "principal for [107.960666, 59.4105, 5.777165] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 85.2416, annual rate 160.878 and time 2.69428?", + "a": "0.1966577874515238", + "valid": true, + "kind": "compute", + "expect": 0.1966577874515238, + "dtype": "quantity", + "unit": "$", + "why": "principal for [85.241623, 160.878442, 2.69428] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 85.2416, annual rate of 160.878 and time of 2.69428.", + "a": "0.1966577874515238", + "valid": true, + "kind": "compute", + "expect": 0.1966577874515238, + "dtype": "quantity", + "unit": "$", + "why": "principal for [85.241623, 160.878442, 2.69428] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 45.6157, annual rate 4.97131 and time 94.305?", + "a": "0.0972990278496778", + "valid": true, + "kind": "compute", + "expect": 0.0972990278496778, + "dtype": "quantity", + "unit": "$", + "why": "principal for [45.61567, 4.971307, 94.305046] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 45.6157, annual rate of 4.97131 and time of 94.305.", + "a": "0.0972990278496778", + "valid": true, + "kind": "compute", + "expect": 0.0972990278496778, + "dtype": "quantity", + "unit": "$", + "why": "principal for [45.61567, 4.971307, 94.305046] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 10.5638, annual rate 198.839 and time 0.671697?", + "a": "0.07909461512056758", + "valid": true, + "kind": "compute", + "expect": 0.07909461512056758, + "dtype": "quantity", + "unit": "$", + "why": "principal for [10.563843, 198.838955, 0.671697] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 10.5638, annual rate of 198.839 and time of 0.671697.", + "a": "0.07909461512056758", + "valid": true, + "kind": "compute", + "expect": 0.07909461512056758, + "dtype": "quantity", + "unit": "$", + "why": "principal for [10.563843, 198.838955, 0.671697] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 21.7931, annual rate 29.5106 and time 8.50341?", + "a": "0.0868457153097377", + "valid": true, + "kind": "compute", + "expect": 0.0868457153097377, + "dtype": "quantity", + "unit": "$", + "why": "principal for [21.793126, 29.510609, 8.503407] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 21.7931, annual rate of 29.5106 and time of 8.50341.", + "a": "0.0868457153097377", + "valid": true, + "kind": "compute", + "expect": 0.0868457153097377, + "dtype": "quantity", + "unit": "$", + "why": "principal for [21.793126, 29.510609, 8.503407] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 223.509, annual rate 17.3414 and time 7.10705?", + "a": "1.8135113064708561", + "valid": true, + "kind": "compute", + "expect": 1.8135113064708561, + "dtype": "quantity", + "unit": "$", + "why": "principal for [223.508796, 17.341435, 7.107049] (the system Simple interest)" + }, + { + "q": "Tell me the principal with interest of 223.509, annual rate of 17.3414 and time of 7.10705.", + "a": "1.8135113064708561", + "valid": true, + "kind": "compute", + "expect": 1.8135113064708561, + "dtype": "quantity", + "unit": "$", + "why": "principal for [223.508796, 17.341435, 7.107049] (the system Simple interest)" + }, + { + "q": "What is the principal for interest 107.961 and annual rate 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Tell me the principal with interest of 85.2416 and annual rate of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "What is the principal of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the principal of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the principal with interest of -45.6157, annual rate of 4.97131 and time of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative interest: no example had one" + }, + { + "q": "Which principal is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the interest is 17.7888, annual rate is 167.625 and the time is 10.3291, what is the principal?", + "a": "0.010274173498684695", + "valid": true, + "kind": "compute", + "expect": 0.010274173498684695, + "dtype": "quantity", + "unit": "$", + "why": "principal for [17.788778, 167.624948, 10.329054] (the system Simple interest)" + }, + { + "q": "Could you work out the principal given interest = 17.7888, annual rate = 167.625, time = 10.3291?", + "a": "0.010274173498684695", + "valid": true, + "kind": "compute", + "expect": 0.010274173498684695, + "dtype": "quantity", + "unit": "$", + "why": "principal for [17.788778, 167.624948, 10.329054] (the system Simple interest)" + }, + { + "q": "I need the principal for an interest of 21.511, an annual rate of 173.394 and a time of 251.084, please.", + "a": "0.0004940929501514961", + "valid": true, + "kind": "compute", + "expect": 0.0004940929501514961, + "dtype": "quantity", + "unit": "$", + "why": "principal for [21.511016, 173.393638, 251.084037] (the system Simple interest)" + }, + { + "q": "If the interest is 21.511, annual rate is 173.394 and the time is 251.084, what is the principal?", + "a": "0.0004940929501514961", + "valid": true, + "kind": "compute", + "expect": 0.0004940929501514961, + "dtype": "quantity", + "unit": "$", + "why": "principal for [21.511016, 173.393638, 251.084037] (the system Simple interest)" + }, + { + "q": "Could you work out the principal given interest = 129.245, annual rate = 1.18359, time = 15.9416?", + "a": "6.849836414751196", + "valid": true, + "kind": "compute", + "expect": 6.849836414751196, + "dtype": "quantity", + "unit": "$", + "why": "principal for [129.244984, 1.18359, 15.941612] (the system Simple interest)" + }, + { + "q": "I need the principal for an interest of 129.245, an annual rate of 1.18359 and a time of 15.9416, please.", + "a": "6.849836414751196", + "valid": true, + "kind": "compute", + "expect": 6.849836414751196, + "dtype": "quantity", + "unit": "$", + "why": "principal for [129.244984, 1.18359, 15.941612] (the system Simple interest)" + }, + { + "q": "If the interest is 20.3966, annual rate is 18.3169 and the time is 6.8386, what is the principal?", + "a": "0.16283157083473473", + "valid": true, + "kind": "compute", + "expect": 0.16283157083473473, + "dtype": "quantity", + "unit": "$", + "why": "principal for [20.396558, 18.316867, 6.838598] (the system Simple interest)" + }, + { + "q": "Could you work out the principal given interest = 20.3966, annual rate = 18.3169, time = 6.8386?", + "a": "0.16283157083473473", + "valid": true, + "kind": "compute", + "expect": 0.16283157083473473, + "dtype": "quantity", + "unit": "$", + "why": "principal for [20.396558, 18.316867, 6.838598] (the system Simple interest)" + }, + { + "q": "I need the principal for an interest of 185.886, an annual rate of 13.2373 and a time of 4.71941, please.", + "a": "2.975496158535072", + "valid": true, + "kind": "compute", + "expect": 2.975496158535072, + "dtype": "quantity", + "unit": "$", + "why": "principal for [185.886273, 13.237311, 4.719415] (the system Simple interest)" + }, + { + "q": "If the interest is 185.886, annual rate is 13.2373 and the time is 4.71941, what is the principal?", + "a": "2.975496158535072", + "valid": true, + "kind": "compute", + "expect": 2.975496158535072, + "dtype": "quantity", + "unit": "$", + "why": "principal for [185.886273, 13.237311, 4.719415] (the system Simple interest)" + }, + { + "q": "Could you work out the principal given interest = 9.1061, annual rate = 24.5721, time = 108.451?", + "a": "0.0034171013315116693", + "valid": true, + "kind": "compute", + "expect": 0.0034171013315116693, + "dtype": "quantity", + "unit": "$", + "why": "principal for [9.106104, 24.572086, 108.450792] (the system Simple interest)" + }, + { + "q": "I need the principal for an interest of 9.1061, an annual rate of 24.5721 and a time of 108.451, please.", + "a": "0.0034171013315116693", + "valid": true, + "kind": "compute", + "expect": 0.0034171013315116693, + "dtype": "quantity", + "unit": "$", + "why": "principal for [9.106104, 24.572086, 108.450792] (the system Simple interest)" + }, + { + "q": "If the interest is 17.7888 and the annual rate is 167.625, what is the principal?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Could you work out the principal given interest = 21.511, annual rate = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Do you know the principal of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the principal of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the principal given interest = -129.245, annual rate = 1.18359, time = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative interest: no example had one" + }, + { + "q": "What is a typical principal?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-principal/program.py b/root/organs10/physics/specialists/solved-principal/program.py new file mode 100644 index 0000000000000000000000000000000000000000..436a80e5ce8f12e0f27d305675d214660b4f9a9d --- /dev/null +++ b/root/organs10/physics/specialists/solved-principal/program.py @@ -0,0 +1,7 @@ +"""principal from interest, annual rate, time (Simple interest) +The maths organ (systems.py): solved from the system I = P*r*t; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(interest, annual_rate, time): + return 1.0*interest/(annual_rate*time) diff --git a/root/organs10/physics/specialists/solved-principal/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-principal/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-principal/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-proper-distance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-proper-distance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-proper-distance/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-proper-distance/panel.json b/root/organs10/physics/specialists/solved-proper-distance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..289cf6f2872fe6f74a1e347aa76de07c062f52c7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-proper-distance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the proper distance for Hubble's constant 107.961 and recessional velocity 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [107.960666, 59.4105] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 107.961 and recessional velocity of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [107.960666, 59.4105] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 169.527 and recessional velocity 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [169.526958, 280.773702] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 169.527 and recessional velocity of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [169.526958, 280.773702] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 1.91195 and recessional velocity 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [1.911952, 82.240072] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 1.91195 and recessional velocity of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [1.911952, 82.240072] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 1.64379 and recessional velocity 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [1.643795, 252.709024] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 1.64379 and recessional velocity of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [1.643795, 252.709024] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 18.3169 and recessional velocity 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [18.316867, 6.838598] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 18.3169 and recessional velocity of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [18.316867, 6.838598] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 156.502 and recessional velocity 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [156.50181, 185.886273] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 156.502 and recessional velocity of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [156.50181, 185.886273] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the proper distance for Hubble's constant 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the recessional velocity is not given" + }, + { + "q": "Tell me the proper distance with Hubble's constant of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the recessional velocity is not given" + }, + { + "q": "What is the proper distance of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the proper distance of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the proper distance with Hubble's constant of -1.91195 and recessional velocity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Hubble's constant: no example had one" + }, + { + "q": "Which proper distance is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the Hubble's constant is 8.50728 and the recessional velocity is 17.7888, what is the proper distance?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [8.507283, 17.788778] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = 8.50728, recessional velocity = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [8.507283, 17.788778] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the proper distance for a Hubble's constant of 8.24951 and a recessional velocity of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [8.24951, 0.634021] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 8.24951 and the recessional velocity is 0.634021, what is the proper distance?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [8.24951, 0.634021] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = 0.318734, recessional velocity = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [0.318734, 9.566071] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the proper distance for a Hubble's constant of 0.318734 and a recessional velocity of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [0.318734, 9.566071] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 0.671697 and the recessional velocity is 14.2496, what is the proper distance?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [0.671697, 14.249569] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = 0.671697, recessional velocity = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [0.671697, 14.249569] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the proper distance for a Hubble's constant of 21.7931 and a recessional velocity of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [21.793126, 29.510609] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 21.7931 and the recessional velocity is 29.5106, what is the proper distance?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [21.793126, 29.510609] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = 153.15, recessional velocity = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [153.149965, 18.595315] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the proper distance for a Hubble's constant of 153.15 and a recessional velocity of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m", + "why": "proper distance for [153.149965, 18.595315] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 8.50728, what is the proper distance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the recessional velocity is not given" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the recessional velocity is not given" + }, + { + "q": "Do you know the proper distance of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the proper distance of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the proper distance given Hubble's constant = -0.318734, recessional velocity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Hubble's constant: no example had one" + }, + { + "q": "What is a typical proper distance?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-proper-distance/program.py b/root/organs10/physics/specialists/solved-proper-distance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a33f7c50ab76263314a4e175c309d5dfca3b9b51 --- /dev/null +++ b/root/organs10/physics/specialists/solved-proper-distance/program.py @@ -0,0 +1,7 @@ +"""proper distance from Hubble's constant, recessional velocity (Hubble–Lemaître law (Wikidata Q179916)) +The maths organ (systems.py): solved from the system q1 = q0*q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(hubble_s_constant, recessional_velocity): + return 1.0*recessional_velocity/hubble_s_constant diff --git a/root/organs10/physics/specialists/solved-proper-distance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-proper-distance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-proper-distance/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-q10470221/organ_formula_v2.py b/root/organs10/physics/specialists/solved-q10470221/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-q10470221/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-q10470221/panel.json b/root/organs10/physics/specialists/solved-q10470221/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b2019bc347c4ad600e998bf68f96f1ad22b2d021 --- /dev/null +++ b/root/organs10/physics/specialists/solved-q10470221/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Q10470221 for signal bandwidth 107.961?", + "a": "53.98033294498101", + "valid": true, + "kind": "compute", + "expect": 53.98033294498101, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [107.960666] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 107.961.", + "a": "53.98033294498101", + "valid": true, + "kind": "compute", + "expect": 53.98033294498101, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [107.960666] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221 for signal bandwidth 22.652?", + "a": "11.326011398427896", + "valid": true, + "kind": "compute", + "expect": 11.326011398427896, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [22.652023] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 22.652.", + "a": "11.326011398427896", + "valid": true, + "kind": "compute", + "expect": 11.326011398427896, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [22.652023] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221 for signal bandwidth 173.394?", + "a": "86.69681920265126", + "valid": true, + "kind": "compute", + "expect": 86.69681920265126, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [173.393638] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 173.394.", + "a": "86.69681920265126", + "valid": true, + "kind": "compute", + "expect": 86.69681920265126, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [173.393638] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221 for signal bandwidth 126.709?", + "a": "63.354625900091186", + "valid": true, + "kind": "compute", + "expect": 63.354625900091186, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [126.709252] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 126.709.", + "a": "63.354625900091186", + "valid": true, + "kind": "compute", + "expect": 63.354625900091186, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [126.709252] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221 for signal bandwidth 0.671697?", + "a": "0.33584859989709676", + "valid": true, + "kind": "compute", + "expect": 0.33584859989709676, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [0.671697] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 0.671697.", + "a": "0.33584859989709676", + "valid": true, + "kind": "compute", + "expect": 0.33584859989709676, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [0.671697] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221 for signal bandwidth 1.16997?", + "a": "0.5849840029889679", + "valid": true, + "kind": "compute", + "expect": 0.5849840029889679, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [1.169968] (the system None (Wikidata Q10470221))" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of 1.16997.", + "a": "0.5849840029889679", + "valid": true, + "kind": "compute", + "expect": 0.5849840029889679, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [1.169968] (the system None (Wikidata Q10470221))" + }, + { + "q": "What is the Q10470221?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the signal bandwidth is not given" + }, + { + "q": "Could you work out the Q10470221, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the signal bandwidth is not given" + }, + { + "q": "What is the Q10470221 of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Q10470221 of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Q10470221 with signal bandwidth of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative signal bandwidth: no example had one" + }, + { + "q": "Which Q10470221 is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the signal bandwidth is 2.57003, what is the Q10470221?", + "a": "1.2850149566518219", + "valid": true, + "kind": "compute", + "expect": 1.2850149566518219, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [2.57003] (the system None (Wikidata Q10470221))" + }, + { + "q": "Could you work out the Q10470221 given signal bandwidth = 2.57003?", + "a": "1.2850149566518219", + "valid": true, + "kind": "compute", + "expect": 1.2850149566518219, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [2.57003] (the system None (Wikidata Q10470221))" + }, + { + "q": "I need the Q10470221 for a signal bandwidth of 48.921, please.", + "a": "24.460495430005917", + "valid": true, + "kind": "compute", + "expect": 24.460495430005917, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [48.920991] (the system None (Wikidata Q10470221))" + }, + { + "q": "If the signal bandwidth is 48.921, what is the Q10470221?", + "a": "24.460495430005917", + "valid": true, + "kind": "compute", + "expect": 24.460495430005917, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [48.920991] (the system None (Wikidata Q10470221))" + }, + { + "q": "Could you work out the Q10470221 given signal bandwidth = 0.348438?", + "a": "0.17421883481501524", + "valid": true, + "kind": "compute", + "expect": 0.17421883481501524, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [0.348438] (the system None (Wikidata Q10470221))" + }, + { + "q": "I need the Q10470221 for a signal bandwidth of 0.348438, please.", + "a": "0.17421883481501524", + "valid": true, + "kind": "compute", + "expect": 0.17421883481501524, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [0.348438] (the system None (Wikidata Q10470221))" + }, + { + "q": "If the signal bandwidth is 252.709, what is the Q10470221?", + "a": "126.35451212476376", + "valid": true, + "kind": "compute", + "expect": 126.35451212476376, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [252.709024] (the system None (Wikidata Q10470221))" + }, + { + "q": "Could you work out the Q10470221 given signal bandwidth = 252.709?", + "a": "126.35451212476376", + "valid": true, + "kind": "compute", + "expect": 126.35451212476376, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [252.709024] (the system None (Wikidata Q10470221))" + }, + { + "q": "I need the Q10470221 for a signal bandwidth of 20.3966, please.", + "a": "10.19827898098172", + "valid": true, + "kind": "compute", + "expect": 10.19827898098172, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [20.396558] (the system None (Wikidata Q10470221))" + }, + { + "q": "If the signal bandwidth is 20.3966, what is the Q10470221?", + "a": "10.19827898098172", + "valid": true, + "kind": "compute", + "expect": 10.19827898098172, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [20.396558] (the system None (Wikidata Q10470221))" + }, + { + "q": "Could you work out the Q10470221 given signal bandwidth = 134.993?", + "a": "67.496478790369", + "valid": true, + "kind": "compute", + "expect": 67.496478790369, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [134.992958] (the system None (Wikidata Q10470221))" + }, + { + "q": "I need the Q10470221 for a signal bandwidth of 134.993, please.", + "a": "67.496478790369", + "valid": true, + "kind": "compute", + "expect": 67.496478790369, + "dtype": "quantity", + "unit": "Hz", + "why": "Q10470221 for [134.992958] (the system None (Wikidata Q10470221))" + }, + { + "q": "I need the Q10470221, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the signal bandwidth is not given" + }, + { + "q": "Can you tell me the Q10470221?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the signal bandwidth is not given" + }, + { + "q": "Do you know the Q10470221 of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Q10470221 of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Q10470221 given signal bandwidth = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative signal bandwidth: no example had one" + }, + { + "q": "What is a typical Q10470221?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-q10470221/program.py b/root/organs10/physics/specialists/solved-q10470221/program.py new file mode 100644 index 0000000000000000000000000000000000000000..9172733770638cbfdbcb7d355dc5dad49f24bd58 --- /dev/null +++ b/root/organs10/physics/specialists/solved-q10470221/program.py @@ -0,0 +1,7 @@ +"""Q10470221 from signal bandwidth (None (Wikidata Q10470221)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(signal_bandwidth): + return 0.5*signal_bandwidth diff --git a/root/organs10/physics/specialists/solved-q10470221/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-q10470221/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-q10470221/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-quality-factor-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-quality-factor-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-quality-factor-2/panel.json b/root/organs10/physics/specialists/solved-quality-factor-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..802cdca25353bf92a8f55f98f1ff0c6a42c24ab9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the quality factor for loss factor 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [107.960666] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [107.960666] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor for loss factor 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [22.652023] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [22.652023] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor for loss factor 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [173.393638] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [173.393638] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor for loss factor 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [126.709252] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [126.709252] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor for loss factor 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.671697] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.671697] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor for loss factor 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.169968] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Tell me the quality factor with loss factor of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.169968] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "What is the quality factor?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the loss factor is not given" + }, + { + "q": "Could you work out the quality factor, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the loss factor is not given" + }, + { + "q": "What is the quality factor of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the quality factor of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the quality factor with loss factor of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative loss factor: no example had one" + }, + { + "q": "Which quality factor is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the loss factor is 2.57003, what is the quality factor?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [2.57003] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Could you work out the quality factor given loss factor = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [2.57003] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "I need the quality factor for a loss factor of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [48.920991] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "If the loss factor is 48.921, what is the quality factor?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [48.920991] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Could you work out the quality factor given loss factor = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.348438] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "I need the quality factor for a loss factor of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.348438] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "If the loss factor is 252.709, what is the quality factor?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [252.709024] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Could you work out the quality factor given loss factor = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [252.709024] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "I need the quality factor for a loss factor of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [20.396558] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "If the loss factor is 20.3966, what is the quality factor?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [20.396558] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "Could you work out the quality factor given loss factor = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [134.992958] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "I need the quality factor for a loss factor of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [134.992958] (the system loss factor (Wikidata Q79468728))" + }, + { + "q": "I need the quality factor, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the loss factor is not given" + }, + { + "q": "Can you tell me the quality factor?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the loss factor is not given" + }, + { + "q": "Do you know the quality factor of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the quality factor of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the quality factor given loss factor = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative loss factor: no example had one" + }, + { + "q": "What is a typical quality factor?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-quality-factor-2/program.py b/root/organs10/physics/specialists/solved-quality-factor-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb97780535d80647bcf36e1c4c374d757fe5e27 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor-2/program.py @@ -0,0 +1,7 @@ +"""quality factor from loss factor (loss factor (Wikidata Q79468728)) +The maths organ (systems.py): solved from the system q0 = ((1)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(loss_factor): + return 1.0/loss_factor diff --git a/root/organs10/physics/specialists/solved-quality-factor-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-quality-factor-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-quality-factor/organ_formula_v2.py b/root/organs10/physics/specialists/solved-quality-factor/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-quality-factor/panel.json b/root/organs10/physics/specialists/solved-quality-factor/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..65895fb82bbe0e8cf1b1d8a071836c7d80ab8ef1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the quality factor for dose equivalent 107.961 and absorbed dose 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [107.960666, 59.4105] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 107.961 and absorbed dose of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [107.960666, 59.4105] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 169.527 and absorbed dose 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [169.526958, 280.773702] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 169.527 and absorbed dose of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [169.526958, 280.773702] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 1.91195 and absorbed dose 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.911952, 82.240072] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 1.91195 and absorbed dose of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.911952, 82.240072] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 1.64379 and absorbed dose 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.643795, 252.709024] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 1.64379 and absorbed dose of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [1.643795, 252.709024] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 18.3169 and absorbed dose 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [18.316867, 6.838598] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 18.3169 and absorbed dose of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [18.316867, 6.838598] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 156.502 and absorbed dose 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [156.50181, 185.886273] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Tell me the quality factor with dose equivalent of 156.502 and absorbed dose of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [156.50181, 185.886273] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "What is the quality factor for dose equivalent 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Tell me the quality factor with dose equivalent of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "What is the quality factor of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the quality factor of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the quality factor with dose equivalent of -1.91195 and absorbed dose of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative dose equivalent: no example had one" + }, + { + "q": "Which quality factor is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the dose equivalent is 8.50728 and the absorbed dose is 17.7888, what is the quality factor?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [8.507283, 17.788778] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Could you work out the quality factor given dose equivalent = 8.50728, absorbed dose = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [8.507283, 17.788778] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "I need the quality factor for a dose equivalent of 8.24951 and an absorbed dose of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [8.24951, 0.634021] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "If the dose equivalent is 8.24951 and the absorbed dose is 0.634021, what is the quality factor?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [8.24951, 0.634021] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Could you work out the quality factor given dose equivalent = 0.318734, absorbed dose = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.318734, 9.566071] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "I need the quality factor for a dose equivalent of 0.318734 and an absorbed dose of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.318734, 9.566071] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "If the dose equivalent is 0.671697 and the absorbed dose is 14.2496, what is the quality factor?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.671697, 14.249569] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Could you work out the quality factor given dose equivalent = 0.671697, absorbed dose = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [0.671697, 14.249569] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "I need the quality factor for a dose equivalent of 21.7931 and an absorbed dose of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [21.793126, 29.510609] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "If the dose equivalent is 21.7931 and the absorbed dose is 29.5106, what is the quality factor?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [21.793126, 29.510609] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "Could you work out the quality factor given dose equivalent = 153.15, absorbed dose = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [153.149965, 18.595315] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "I need the quality factor for a dose equivalent of 153.15 and an absorbed dose of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "quality factor for [153.149965, 18.595315] (the system dose equivalent (Wikidata Q256106))" + }, + { + "q": "If the dose equivalent is 8.50728, what is the quality factor?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Could you work out the quality factor given dose equivalent = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Do you know the quality factor of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the quality factor of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the quality factor given dose equivalent = -0.318734, absorbed dose = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative dose equivalent: no example had one" + }, + { + "q": "What is a typical quality factor?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-quality-factor/program.py b/root/organs10/physics/specialists/solved-quality-factor/program.py new file mode 100644 index 0000000000000000000000000000000000000000..50974f5a84b30483997cf8024521ee207ca7b612 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor/program.py @@ -0,0 +1,7 @@ +"""quality factor from dose equivalent, absorbed dose (dose equivalent (Wikidata Q256106)) +The maths organ (systems.py): solved from the system q0 = q1*q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(dose_equivalent, absorbed_dose): + return 1.0*dose_equivalent/absorbed_dose diff --git a/root/organs10/physics/specialists/solved-quality-factor/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-quality-factor/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quality-factor/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-quantity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-quantity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quantity/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-quantity/panel.json b/root/organs10/physics/specialists/solved-quantity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b25562e0255759895fa3f05ed61ff6a690a9d61e --- /dev/null +++ b/root/organs10/physics/specialists/solved-quantity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the quantity for revenue 107.961 and unit price 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [107.960666, 59.4105] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 107.961 and unit price of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [107.960666, 59.4105] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 169.527 and unit price 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [169.526958, 280.773702] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 169.527 and unit price of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [169.526958, 280.773702] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 1.91195 and unit price 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [1.911952, 82.240072] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 1.91195 and unit price of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [1.911952, 82.240072] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 1.64379 and unit price 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [1.643795, 252.709024] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 1.64379 and unit price of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [1.643795, 252.709024] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 18.3169 and unit price 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [18.316867, 6.838598] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 18.3169 and unit price of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [18.316867, 6.838598] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 156.502 and unit price 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [156.50181, 185.886273] (the system Revenue)" + }, + { + "q": "Tell me the quantity with revenue of 156.502 and unit price of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [156.50181, 185.886273] (the system Revenue)" + }, + { + "q": "What is the quantity for revenue 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the unit price is not given" + }, + { + "q": "Tell me the quantity with revenue of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the unit price is not given" + }, + { + "q": "What is the quantity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the quantity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the quantity with revenue of -1.91195 and unit price of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative revenue: no example had one" + }, + { + "q": "Which quantity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the revenue is 8.50728 and the unit price is 17.7888, what is the quantity?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [8.507283, 17.788778] (the system Revenue)" + }, + { + "q": "Could you work out the quantity given revenue = 8.50728, unit price = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [8.507283, 17.788778] (the system Revenue)" + }, + { + "q": "I need the quantity for a revenue of 8.24951 and an unit price of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [8.24951, 0.634021] (the system Revenue)" + }, + { + "q": "If the revenue is 8.24951 and the unit price is 0.634021, what is the quantity?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [8.24951, 0.634021] (the system Revenue)" + }, + { + "q": "Could you work out the quantity given revenue = 0.318734, unit price = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [0.318734, 9.566071] (the system Revenue)" + }, + { + "q": "I need the quantity for a revenue of 0.318734 and an unit price of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [0.318734, 9.566071] (the system Revenue)" + }, + { + "q": "If the revenue is 0.671697 and the unit price is 14.2496, what is the quantity?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [0.671697, 14.249569] (the system Revenue)" + }, + { + "q": "Could you work out the quantity given revenue = 0.671697, unit price = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [0.671697, 14.249569] (the system Revenue)" + }, + { + "q": "I need the quantity for a revenue of 21.7931 and an unit price of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [21.793126, 29.510609] (the system Revenue)" + }, + { + "q": "If the revenue is 21.7931 and the unit price is 29.5106, what is the quantity?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [21.793126, 29.510609] (the system Revenue)" + }, + { + "q": "Could you work out the quantity given revenue = 153.15, unit price = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [153.149965, 18.595315] (the system Revenue)" + }, + { + "q": "I need the quantity for a revenue of 153.15 and an unit price of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "quantity for [153.149965, 18.595315] (the system Revenue)" + }, + { + "q": "If the revenue is 8.50728, what is the quantity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the unit price is not given" + }, + { + "q": "Could you work out the quantity given revenue = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the unit price is not given" + }, + { + "q": "Do you know the quantity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the quantity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the quantity given revenue = -0.318734, unit price = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative revenue: no example had one" + }, + { + "q": "What is a typical quantity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-quantity/program.py b/root/organs10/physics/specialists/solved-quantity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f98e86ca3ce6ae308784a1282f6e869d882481 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quantity/program.py @@ -0,0 +1,7 @@ +"""quantity from revenue, unit price (Revenue) +The maths organ (systems.py): solved from the system R = p*q; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(revenue, unit_price): + return 1.0*revenue/unit_price diff --git a/root/organs10/physics/specialists/solved-quantity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-quantity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-quantity/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiant-efficiency/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiant-efficiency/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-efficiency/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiant-efficiency/panel.json b/root/organs10/physics/specialists/solved-radiant-efficiency/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6015e27cb7b070ecc0cb678216929909786b7d54 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-efficiency/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiant efficiency for radiant flux 107.961 and power 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 107.961 and power of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 169.527 and power 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 169.527 and power of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 1.91195 and power 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 1.91195 and power of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 1.64379 and power 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 1.64379 and power of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 18.3169 and power 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 18.3169 and power of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 156.502 and power 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 156.502 and power of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant efficiency for radiant flux 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the radiant efficiency of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiant efficiency of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiant efficiency with radiant flux of -1.91195 and power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant flux: no example had one" + }, + { + "q": "Which radiant efficiency is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiant flux is 8.50728 and the power is 17.7888, what is the radiant efficiency?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = 8.50728, power = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant efficiency for a radiant flux of 8.24951 and a power of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant flux is 8.24951 and the power is 0.634021, what is the radiant efficiency?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = 0.318734, power = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant efficiency for a radiant flux of 0.318734 and a power of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant flux is 0.671697 and the power is 14.2496, what is the radiant efficiency?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = 0.671697, power = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant efficiency for a radiant flux of 21.7931 and a power of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant flux is 21.7931 and the power is 29.5106, what is the radiant efficiency?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = 153.15, power = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant efficiency for a radiant flux of 153.15 and a power of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "radiant efficiency for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant flux is 8.50728, what is the radiant efficiency?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the radiant efficiency of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiant efficiency of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiant efficiency given radiant flux = -0.318734, power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant flux: no example had one" + }, + { + "q": "What is a typical radiant efficiency?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiant-efficiency/program.py b/root/organs10/physics/specialists/solved-radiant-efficiency/program.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1982699e797f8e9f5998d3b4bf1f741a6c2d00 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-efficiency/program.py @@ -0,0 +1,7 @@ +"""radiant efficiency from radiant flux, power (radiant efficiency (Wikidata Q7962586)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiant_flux, power): + return 1.0*radiant_flux/power diff --git a/root/organs10/physics/specialists/solved-radiant-efficiency/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiant-efficiency/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-efficiency/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/panel.json b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..221e6975b3c6e29cd72d886b28c7aa87f64b03f2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 107.961 and radiant exitance 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [107.960666, 59.4105] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 107.961 and radiant exitance of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [107.960666, 59.4105] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 169.527 and radiant exitance 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [169.526958, 280.773702] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 169.527 and radiant exitance of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [169.526958, 280.773702] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 1.91195 and radiant exitance 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [1.911952, 82.240072] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 1.91195 and radiant exitance of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [1.911952, 82.240072] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 1.64379 and radiant exitance 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [1.643795, 252.709024] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 1.64379 and radiant exitance of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [1.643795, 252.709024] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 18.3169 and radiant exitance 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [18.316867, 6.838598] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 18.3169 and radiant exitance of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [18.316867, 6.838598] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 156.502 and radiant exitance 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [156.50181, 185.886273] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 156.502 and radiant exitance of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [156.50181, 185.886273] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance of a Planckian radiator for spectral emissivity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant exitance is not given" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant exitance is not given" + }, + { + "q": "What is the radiant exitance of a Planckian radiator of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiant exitance of a Planckian radiator of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiant exitance of a Planckian radiator with spectral emissivity of -1.91195 and radiant exitance of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative spectral emissivity: no example had one" + }, + { + "q": "Which radiant exitance of a Planckian radiator is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the spectral emissivity is 8.50728 and the radiant exitance is 17.7888, what is the radiant exitance of a Planckian radiator?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [8.507283, 17.788778] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = 8.50728, radiant exitance = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [8.507283, 17.788778] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance of a Planckian radiator for a spectral emissivity of 8.24951 and a radiant exitance of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [8.24951, 0.634021] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the spectral emissivity is 8.24951 and the radiant exitance is 0.634021, what is the radiant exitance of a Planckian radiator?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [8.24951, 0.634021] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = 0.318734, radiant exitance = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [0.318734, 9.566071] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance of a Planckian radiator for a spectral emissivity of 0.318734 and a radiant exitance of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [0.318734, 9.566071] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the spectral emissivity is 0.671697 and the radiant exitance is 14.2496, what is the radiant exitance of a Planckian radiator?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [0.671697, 14.249569] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = 0.671697, radiant exitance = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [0.671697, 14.249569] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance of a Planckian radiator for a spectral emissivity of 21.7931 and a radiant exitance of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [21.793126, 29.510609] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the spectral emissivity is 21.7931 and the radiant exitance is 29.5106, what is the radiant exitance of a Planckian radiator?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [21.793126, 29.510609] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = 153.15, radiant exitance = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [153.149965, 18.595315] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance of a Planckian radiator for a spectral emissivity of 153.15 and a radiant exitance of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance of a Planckian radiator for [153.149965, 18.595315] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the spectral emissivity is 8.50728, what is the radiant exitance of a Planckian radiator?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant exitance is not given" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiant exitance is not given" + }, + { + "q": "Do you know the radiant exitance of a Planckian radiator of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiant exitance of a Planckian radiator of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiant exitance of a Planckian radiator given spectral emissivity = -0.318734, radiant exitance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative spectral emissivity: no example had one" + }, + { + "q": "What is a typical radiant exitance of a Planckian radiator?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/program.py b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/program.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1ba1d904511166081cb52969eb63be595c4c40 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/program.py @@ -0,0 +1,7 @@ +"""radiant exitance of a Planckian radiator from spectral emissivity, radiant exitance (spectral emissivity (Wikidata Q84710157)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(spectral_emissivity, radiant_exitance): + return 1.0*radiant_exitance/spectral_emissivity diff --git a/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance-of-a-plancki/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiant-exitance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiant-exitance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiant-exitance/panel.json b/root/organs10/physics/specialists/solved-radiant-exitance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e13bcb65dee1b052a8b60074250ad80ed1bbcdb7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 107.961 and spectral emissivity 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [107.960666, 59.4105] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 107.961 and spectral emissivity of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [107.960666, 59.4105] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 169.527 and spectral emissivity 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [169.526958, 280.773702] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 169.527 and spectral emissivity of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [169.526958, 280.773702] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 1.91195 and spectral emissivity 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [1.911952, 82.240072] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 1.91195 and spectral emissivity of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [1.911952, 82.240072] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 1.64379 and spectral emissivity 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [1.643795, 252.709024] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 1.64379 and spectral emissivity of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [1.643795, 252.709024] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 18.3169 and spectral emissivity 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [18.316867, 6.838598] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 18.3169 and spectral emissivity of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [18.316867, 6.838598] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 156.502 and spectral emissivity 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [156.50181, 185.886273] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 156.502 and spectral emissivity of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [156.50181, 185.886273] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "What is the radiant exitance for radiant exitance of a Planckian radiator 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the spectral emissivity is not given" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the spectral emissivity is not given" + }, + { + "q": "What is the radiant exitance of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiant exitance of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiant exitance with radiant exitance of a Planckian radiator of -1.91195 and spectral emissivity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant exitance of a Planckian radiator: no example had one" + }, + { + "q": "Which radiant exitance is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiant exitance of a Planckian radiator is 8.50728 and the spectral emissivity is 17.7888, what is the radiant exitance?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [8.507283, 17.788778] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = 8.50728, spectral emissivity = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [8.507283, 17.788778] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance for a radiant exitance of a Planckian radiator of 8.24951 and a spectral emissivity of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [8.24951, 0.634021] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the radiant exitance of a Planckian radiator is 8.24951 and the spectral emissivity is 0.634021, what is the radiant exitance?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [8.24951, 0.634021] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = 0.318734, spectral emissivity = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [0.318734, 9.566071] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance for a radiant exitance of a Planckian radiator of 0.318734 and a spectral emissivity of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [0.318734, 9.566071] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the radiant exitance of a Planckian radiator is 0.671697 and the spectral emissivity is 14.2496, what is the radiant exitance?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [0.671697, 14.249569] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = 0.671697, spectral emissivity = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [0.671697, 14.249569] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance for a radiant exitance of a Planckian radiator of 21.7931 and a spectral emissivity of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [21.793126, 29.510609] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the radiant exitance of a Planckian radiator is 21.7931 and the spectral emissivity is 29.5106, what is the radiant exitance?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [21.793126, 29.510609] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = 153.15, spectral emissivity = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [153.149965, 18.595315] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "I need the radiant exitance for a radiant exitance of a Planckian radiator of 153.15 and a spectral emissivity of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/s^3", + "why": "radiant exitance for [153.149965, 18.595315] (the system spectral emissivity (Wikidata Q84710157))" + }, + { + "q": "If the radiant exitance of a Planckian radiator is 8.50728, what is the radiant exitance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the spectral emissivity is not given" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the spectral emissivity is not given" + }, + { + "q": "Do you know the radiant exitance of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiant exitance of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiant exitance given radiant exitance of a Planckian radiator = -0.318734, spectral emissivity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant exitance of a Planckian radiator: no example had one" + }, + { + "q": "What is a typical radiant exitance?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiant-exitance/program.py b/root/organs10/physics/specialists/solved-radiant-exitance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ba00075669fd38bbaf1d1aa7c78de625643c795f --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance/program.py @@ -0,0 +1,7 @@ +"""radiant exitance from radiant exitance of a Planckian radiator, spectral emissivity (spectral emissivity (Wikidata Q84710157)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiant_exitance_of_a_planckian_radiator, spectral_emissivity): + return 1.0*radiant_exitance_of_a_planckian_radiator*spectral_emissivity diff --git a/root/organs10/physics/specialists/solved-radiant-exitance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiant-exitance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-exitance/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiant-flux/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiant-flux/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-flux/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiant-flux/panel.json b/root/organs10/physics/specialists/solved-radiant-flux/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..67306935df5148adad8b70ea55b607a11854772a --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-flux/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiant flux for radiant efficiency 107.961 and power 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 107.961 and power of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [107.960666, 59.4105] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 169.527 and power 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 169.527 and power of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [169.526958, 280.773702] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 1.91195 and power 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 1.91195 and power of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [1.911952, 82.240072] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 1.64379 and power 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 1.64379 and power of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [1.643795, 252.709024] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 18.3169 and power 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 18.3169 and power of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [18.316867, 6.838598] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 156.502 and power 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 156.502 and power of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [156.50181, 185.886273] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "What is the radiant flux for radiant efficiency 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the radiant flux of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiant flux of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiant flux with radiant efficiency of -1.91195 and power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant efficiency: no example had one" + }, + { + "q": "Which radiant flux is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiant efficiency is 8.50728 and the power is 17.7888, what is the radiant flux?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = 8.50728, power = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [8.507283, 17.788778] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant flux for a radiant efficiency of 8.24951 and a power of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 8.24951 and the power is 0.634021, what is the radiant flux?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [8.24951, 0.634021] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = 0.318734, power = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant flux for a radiant efficiency of 0.318734 and a power of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [0.318734, 9.566071] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 0.671697 and the power is 14.2496, what is the radiant flux?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = 0.671697, power = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [0.671697, 14.249569] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant flux for a radiant efficiency of 21.7931 and a power of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 21.7931 and the power is 29.5106, what is the radiant flux?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [21.793126, 29.510609] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = 153.15, power = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "I need the radiant flux for a radiant efficiency of 153.15 and a power of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "radiant flux for [153.149965, 18.595315] (the system radiant efficiency (Wikidata Q7962586))" + }, + { + "q": "If the radiant efficiency is 8.50728, what is the radiant flux?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the radiant flux of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiant flux of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiant flux given radiant efficiency = -0.318734, power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiant efficiency: no example had one" + }, + { + "q": "What is a typical radiant flux?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiant-flux/program.py b/root/organs10/physics/specialists/solved-radiant-flux/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5104d782955e1d32dfd9635a40cb3c51ed99b5f2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-flux/program.py @@ -0,0 +1,7 @@ +"""radiant flux from radiant efficiency, power (radiant efficiency (Wikidata Q7962586)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiant_efficiency, power): + return 1.0*power*radiant_efficiency diff --git a/root/organs10/physics/specialists/solved-radiant-flux/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiant-flux/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiant-flux/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/panel.json b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6e3237dccc3c9d10e2e591372402dcf27c834286 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 107.961 and atomic scattering factor 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [107.960666, 59.4105] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 107.961 and atomic scattering factor of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [107.960666, 59.4105] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 169.527 and atomic scattering factor 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [169.526958, 280.773702] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 169.527 and atomic scattering factor of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [169.526958, 280.773702] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 1.91195 and atomic scattering factor 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [1.911952, 82.240072] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 1.91195 and atomic scattering factor of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [1.911952, 82.240072] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 1.64379 and atomic scattering factor 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [1.643795, 252.709024] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 1.64379 and atomic scattering factor of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [1.643795, 252.709024] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 18.3169 and atomic scattering factor 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [18.316867, 6.838598] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 18.3169 and atomic scattering factor of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [18.316867, 6.838598] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 156.502 and atomic scattering factor 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [156.50181, 185.886273] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 156.502 and atomic scattering factor of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [156.50181, 185.886273] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an electron for radiation amplitude scattered by an atom 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "What is the radiation amplitude scattered by an electron of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiation amplitude scattered by an electron of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiation amplitude scattered by an electron with radiation amplitude scattered by an atom of -1.91195 and atomic scattering factor of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiation amplitude scattered by an atom: no example had one" + }, + { + "q": "Which radiation amplitude scattered by an electron is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiation amplitude scattered by an atom is 8.50728 and the atomic scattering factor is 17.7888, what is the radiation amplitude scattered by an electron?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [8.507283, 17.788778] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = 8.50728, atomic scattering factor = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [8.507283, 17.788778] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an electron for a radiation amplitude scattered by an atom of 8.24951 and an atomic scattering factor of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [8.24951, 0.634021] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an atom is 8.24951 and the atomic scattering factor is 0.634021, what is the radiation amplitude scattered by an electron?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [8.24951, 0.634021] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = 0.318734, atomic scattering factor = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [0.318734, 9.566071] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an electron for a radiation amplitude scattered by an atom of 0.318734 and an atomic scattering factor of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [0.318734, 9.566071] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an atom is 0.671697 and the atomic scattering factor is 14.2496, what is the radiation amplitude scattered by an electron?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [0.671697, 14.249569] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = 0.671697, atomic scattering factor = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [0.671697, 14.249569] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an electron for a radiation amplitude scattered by an atom of 21.7931 and an atomic scattering factor of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [21.793126, 29.510609] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an atom is 21.7931 and the atomic scattering factor is 29.5106, what is the radiation amplitude scattered by an electron?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [21.793126, 29.510609] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = 153.15, atomic scattering factor = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [153.149965, 18.595315] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an electron for a radiation amplitude scattered by an atom of 153.15 and an atomic scattering factor of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an electron for [153.149965, 18.595315] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an atom is 8.50728, what is the radiation amplitude scattered by an electron?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Do you know the radiation amplitude scattered by an electron of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiation amplitude scattered by an electron of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiation amplitude scattered by an electron given radiation amplitude scattered by an atom = -0.318734, atomic scattering factor = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiation amplitude scattered by an atom: no example had one" + }, + { + "q": "What is a typical radiation amplitude scattered by an electron?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/program.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8522509218514d407037798baa3640e3e1b48c67 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/program.py @@ -0,0 +1,7 @@ +"""radiation amplitude scattered by an electron from radiation amplitude scattered by an atom, atomic scattering factor (atomic scattering factor (Wikidata Q837866)) +The maths organ (systems.py): solved from the system q2 = ((q0)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiation_amplitude_scattered_by_an_atom, atomic_scattering_factor): + return 1.0*radiation_amplitude_scattered_by_an_atom/atomic_scattering_factor diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/panel.json b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..902b7c5e201bc3d2a92d17b6fb0975fa3f72c180 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 107.961 and atomic scattering factor 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [107.960666, 59.4105] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 107.961 and atomic scattering factor of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [107.960666, 59.4105] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 169.527 and atomic scattering factor 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [169.526958, 280.773702] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 169.527 and atomic scattering factor of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [169.526958, 280.773702] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 1.91195 and atomic scattering factor 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [1.911952, 82.240072] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 1.91195 and atomic scattering factor of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [1.911952, 82.240072] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 1.64379 and atomic scattering factor 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [1.643795, 252.709024] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 1.64379 and atomic scattering factor of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [1.643795, 252.709024] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 18.3169 and atomic scattering factor 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [18.316867, 6.838598] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 18.3169 and atomic scattering factor of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [18.316867, 6.838598] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 156.502 and atomic scattering factor 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [156.50181, 185.886273] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 156.502 and atomic scattering factor of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [156.50181, 185.886273] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "What is the radiation amplitude scattered by an atom for radiation amplitude scattered by an electron 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "What is the radiation amplitude scattered by an atom of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiation amplitude scattered by an atom of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiation amplitude scattered by an atom with radiation amplitude scattered by an electron of -1.91195 and atomic scattering factor of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiation amplitude scattered by an electron: no example had one" + }, + { + "q": "Which radiation amplitude scattered by an atom is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the radiation amplitude scattered by an electron is 8.50728 and the atomic scattering factor is 17.7888, what is the radiation amplitude scattered by an atom?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [8.507283, 17.788778] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = 8.50728, atomic scattering factor = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [8.507283, 17.788778] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an atom for a radiation amplitude scattered by an electron of 8.24951 and an atomic scattering factor of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [8.24951, 0.634021] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an electron is 8.24951 and the atomic scattering factor is 0.634021, what is the radiation amplitude scattered by an atom?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [8.24951, 0.634021] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = 0.318734, atomic scattering factor = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [0.318734, 9.566071] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an atom for a radiation amplitude scattered by an electron of 0.318734 and an atomic scattering factor of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [0.318734, 9.566071] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an electron is 0.671697 and the atomic scattering factor is 14.2496, what is the radiation amplitude scattered by an atom?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [0.671697, 14.249569] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = 0.671697, atomic scattering factor = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [0.671697, 14.249569] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an atom for a radiation amplitude scattered by an electron of 21.7931 and an atomic scattering factor of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [21.793126, 29.510609] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an electron is 21.7931 and the atomic scattering factor is 29.5106, what is the radiation amplitude scattered by an atom?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [21.793126, 29.510609] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = 153.15, atomic scattering factor = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [153.149965, 18.595315] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "I need the radiation amplitude scattered by an atom for a radiation amplitude scattered by an electron of 153.15 and an atomic scattering factor of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "radiation amplitude scattered by an atom for [153.149965, 18.595315] (the system atomic scattering factor (Wikidata Q837866))" + }, + { + "q": "If the radiation amplitude scattered by an electron is 8.50728, what is the radiation amplitude scattered by an atom?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic scattering factor is not given" + }, + { + "q": "Do you know the radiation amplitude scattered by an atom of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiation amplitude scattered by an atom of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiation amplitude scattered by an atom given radiation amplitude scattered by an electron = -0.318734, atomic scattering factor = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative radiation amplitude scattered by an electron: no example had one" + }, + { + "q": "What is a typical radiation amplitude scattered by an atom?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/program.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/program.py new file mode 100644 index 0000000000000000000000000000000000000000..11d9cdde015ca7f8f2149045e49fe12cf5c7cef2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/program.py @@ -0,0 +1,7 @@ +"""radiation amplitude scattered by an atom from radiation amplitude scattered by an electron, atomic scattering factor (atomic scattering factor (Wikidata Q837866)) +The maths organ (systems.py): solved from the system q2 = ((q0)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(radiation_amplitude_scattered_by_an_electron, atomic_scattering_factor): + return 1.0*atomic_scattering_factor*radiation_amplitude_scattered_by_an_electron diff --git a/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-amplitude-scattered/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiation-chemical-yield/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiation-chemical-yield/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-chemical-yield/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiation-chemical-yield/panel.json b/root/organs10/physics/specialists/solved-radiation-chemical-yield/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..cf76d821981a10b7e06f814a479d70f48cec4644 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-chemical-yield/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiation-chemical yield for mean energy imparted 107.961 and amount of substance 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [107.960666, 59.4105] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 107.961 and amount of substance of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [107.960666, 59.4105] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 169.527 and amount of substance 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [169.526958, 280.773702] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 169.527 and amount of substance of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [169.526958, 280.773702] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 1.91195 and amount of substance 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [1.911952, 82.240072] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 1.91195 and amount of substance of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [1.911952, 82.240072] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 1.64379 and amount of substance 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [1.643795, 252.709024] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 1.64379 and amount of substance of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [1.643795, 252.709024] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 18.3169 and amount of substance 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [18.316867, 6.838598] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 18.3169 and amount of substance of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [18.316867, 6.838598] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 156.502 and amount of substance 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [156.50181, 185.886273] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 156.502 and amount of substance of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [156.50181, 185.886273] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "What is the radiation-chemical yield for mean energy imparted 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "What is the radiation-chemical yield of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiation-chemical yield of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiation-chemical yield with mean energy imparted of -1.91195 and amount of substance of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean energy imparted: no example had one" + }, + { + "q": "Which radiation-chemical yield is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mean energy imparted is 8.50728 and the amount of substance is 17.7888, what is the radiation-chemical yield?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [8.507283, 17.788778] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = 8.50728, amount of substance = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [8.507283, 17.788778] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "I need the radiation-chemical yield for a mean energy imparted of 8.24951 and an amount of substance of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [8.24951, 0.634021] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "If the mean energy imparted is 8.24951 and the amount of substance is 0.634021, what is the radiation-chemical yield?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [8.24951, 0.634021] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = 0.318734, amount of substance = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [0.318734, 9.566071] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "I need the radiation-chemical yield for a mean energy imparted of 0.318734 and an amount of substance of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [0.318734, 9.566071] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "If the mean energy imparted is 0.671697 and the amount of substance is 14.2496, what is the radiation-chemical yield?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [0.671697, 14.249569] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = 0.671697, amount of substance = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [0.671697, 14.249569] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "I need the radiation-chemical yield for a mean energy imparted of 21.7931 and an amount of substance of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [21.793126, 29.510609] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "If the mean energy imparted is 21.7931 and the amount of substance is 29.5106, what is the radiation-chemical yield?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [21.793126, 29.510609] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = 153.15, amount of substance = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [153.149965, 18.595315] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "I need the radiation-chemical yield for a mean energy imparted of 153.15 and an amount of substance of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s^2*mol/m^2/kg", + "why": "radiation-chemical yield for [153.149965, 18.595315] (the system radiation-chemical yield (Wikidata Q109061714))" + }, + { + "q": "If the mean energy imparted is 8.50728, what is the radiation-chemical yield?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Do you know the radiation-chemical yield of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiation-chemical yield of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiation-chemical yield given mean energy imparted = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean energy imparted: no example had one" + }, + { + "q": "What is a typical radiation-chemical yield?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiation-chemical-yield/program.py b/root/organs10/physics/specialists/solved-radiation-chemical-yield/program.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd59f75e19de8e4683b4d18093c174c69852c7d --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-chemical-yield/program.py @@ -0,0 +1,7 @@ +"""radiation-chemical yield from mean energy imparted, amount of substance (radiation-chemical yield (Wikidata Q109061714)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mean_energy_imparted, amount_of_substance): + return 1.0*amount_of_substance/mean_energy_imparted diff --git a/root/organs10/physics/specialists/solved-radiation-chemical-yield/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiation-chemical-yield/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-chemical-yield/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radiation-weighting-factor/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radiation-weighting-factor/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-weighting-factor/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radiation-weighting-factor/panel.json b/root/organs10/physics/specialists/solved-radiation-weighting-factor/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..100316690a4c5f03454148045bd67a4a30a35c7d --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-weighting-factor/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radiation weighting factor for organ dose 107.961 and absorbed dose 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [107.960666, 59.4105] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 107.961 and absorbed dose of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [107.960666, 59.4105] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 169.527 and absorbed dose 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [169.526958, 280.773702] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 169.527 and absorbed dose of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [169.526958, 280.773702] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 1.91195 and absorbed dose 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [1.911952, 82.240072] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 1.91195 and absorbed dose of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [1.911952, 82.240072] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 1.64379 and absorbed dose 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [1.643795, 252.709024] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 1.64379 and absorbed dose of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [1.643795, 252.709024] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 18.3169 and absorbed dose 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [18.316867, 6.838598] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 18.3169 and absorbed dose of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [18.316867, 6.838598] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 156.502 and absorbed dose 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [156.50181, 185.886273] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 156.502 and absorbed dose of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [156.50181, 185.886273] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the radiation weighting factor for organ dose 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "What is the radiation weighting factor of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radiation weighting factor of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radiation weighting factor with organ dose of -1.91195 and absorbed dose of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative organ dose: no example had one" + }, + { + "q": "Which radiation weighting factor is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the organ dose is 8.50728 and the absorbed dose is 17.7888, what is the radiation weighting factor?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [8.507283, 17.788778] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = 8.50728, absorbed dose = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [8.507283, 17.788778] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the radiation weighting factor for an organ dose of 8.24951 and an absorbed dose of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [8.24951, 0.634021] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the organ dose is 8.24951 and the absorbed dose is 0.634021, what is the radiation weighting factor?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [8.24951, 0.634021] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = 0.318734, absorbed dose = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [0.318734, 9.566071] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the radiation weighting factor for an organ dose of 0.318734 and an absorbed dose of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [0.318734, 9.566071] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the organ dose is 0.671697 and the absorbed dose is 14.2496, what is the radiation weighting factor?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [0.671697, 14.249569] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = 0.671697, absorbed dose = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [0.671697, 14.249569] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the radiation weighting factor for an organ dose of 21.7931 and an absorbed dose of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [21.793126, 29.510609] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the organ dose is 21.7931 and the absorbed dose is 29.5106, what is the radiation weighting factor?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [21.793126, 29.510609] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = 153.15, absorbed dose = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [153.149965, 18.595315] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the radiation weighting factor for an organ dose of 153.15 and an absorbed dose of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "radiation weighting factor for [153.149965, 18.595315] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the organ dose is 8.50728, what is the radiation weighting factor?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the absorbed dose is not given" + }, + { + "q": "Do you know the radiation weighting factor of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radiation weighting factor of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radiation weighting factor given organ dose = -0.318734, absorbed dose = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative organ dose: no example had one" + }, + { + "q": "What is a typical radiation weighting factor?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radiation-weighting-factor/program.py b/root/organs10/physics/specialists/solved-radiation-weighting-factor/program.py new file mode 100644 index 0000000000000000000000000000000000000000..64822d03d4e1c77440c12d1833c4dbd48ed5ae31 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-weighting-factor/program.py @@ -0,0 +1,7 @@ +"""radiation weighting factor from organ dose, absorbed dose (organ dose (Wikidata Q65242595)) +The maths organ (systems.py): solved from the system q0 = q2*q1; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(organ_dose, absorbed_dose): + return 1.0*organ_dose/absorbed_dose diff --git a/root/organs10/physics/specialists/solved-radiation-weighting-factor/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radiation-weighting-factor/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radiation-weighting-factor/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-10/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-10/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-10/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-10/panel.json b/root/organs10/physics/specialists/solved-radius-10/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ff5e5aee682aa63d0004841f5a57cf652a82825b --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-10/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for volume 107.961 and height 59.4105?", + "a": "0.7605473133697664", + "valid": true, + "kind": "compute", + "expect": 0.7605473133697664, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 107.961 and height of 59.4105.", + "a": "0.7605473133697664", + "valid": true, + "kind": "compute", + "expect": 0.7605473133697664, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 169.527 and height 280.774?", + "a": "0.43839564733214453", + "valid": true, + "kind": "compute", + "expect": 0.43839564733214453, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 169.527 and height of 280.774.", + "a": "0.43839564733214453", + "valid": true, + "kind": "compute", + "expect": 0.43839564733214453, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 1.91195 and height 82.2401?", + "a": "0.08602442704165941", + "valid": true, + "kind": "compute", + "expect": 0.08602442704165941, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 1.91195 and height of 82.2401.", + "a": "0.08602442704165941", + "valid": true, + "kind": "compute", + "expect": 0.08602442704165941, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 1.64379 and height 252.709?", + "a": "0.04550284814281586", + "valid": true, + "kind": "compute", + "expect": 0.04550284814281586, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 1.64379 and height of 252.709.", + "a": "0.04550284814281586", + "valid": true, + "kind": "compute", + "expect": 0.04550284814281586, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 18.3169 and height 6.8386?", + "a": "0.9233516306676184", + "valid": true, + "kind": "compute", + "expect": 0.9233516306676184, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 18.3169 and height of 6.8386.", + "a": "0.9233516306676184", + "valid": true, + "kind": "compute", + "expect": 0.9233516306676184, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 156.502 and height 185.886?", + "a": "0.517679641380687", + "valid": true, + "kind": "compute", + "expect": 0.517679641380687, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Cylinder)" + }, + { + "q": "Tell me the radius with volume of 156.502 and height of 185.886.", + "a": "0.517679641380687", + "valid": true, + "kind": "compute", + "expect": 0.517679641380687, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Cylinder)" + }, + { + "q": "What is the radius for volume 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Tell me the radius with volume of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with volume of -1.91195 and height of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume is 8.50728 and the height is 17.7888, what is the radius?", + "a": "0.39016421620784614", + "valid": true, + "kind": "compute", + "expect": 0.39016421620784614, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Cylinder)" + }, + { + "q": "Could you work out the radius given volume = 8.50728, height = 17.7888?", + "a": "0.39016421620784614", + "valid": true, + "kind": "compute", + "expect": 0.39016421620784614, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Cylinder)" + }, + { + "q": "I need the radius for a volume of 8.24951 and a height of 0.634021, please.", + "a": "2.0351073590826334", + "valid": true, + "kind": "compute", + "expect": 2.0351073590826334, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Cylinder)" + }, + { + "q": "If the volume is 8.24951 and the height is 0.634021, what is the radius?", + "a": "2.0351073590826334", + "valid": true, + "kind": "compute", + "expect": 2.0351073590826334, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Cylinder)" + }, + { + "q": "Could you work out the radius given volume = 0.318734, height = 9.56607?", + "a": "0.10298464894994261", + "valid": true, + "kind": "compute", + "expect": 0.10298464894994261, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Cylinder)" + }, + { + "q": "I need the radius for a volume of 0.318734 and a height of 9.56607, please.", + "a": "0.10298464894994261", + "valid": true, + "kind": "compute", + "expect": 0.10298464894994261, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Cylinder)" + }, + { + "q": "If the volume is 0.671697 and the height is 14.2496, what is the radius?", + "a": "0.12249291319892355", + "valid": true, + "kind": "compute", + "expect": 0.12249291319892355, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Cylinder)" + }, + { + "q": "Could you work out the radius given volume = 0.671697, height = 14.2496?", + "a": "0.12249291319892355", + "valid": true, + "kind": "compute", + "expect": 0.12249291319892355, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Cylinder)" + }, + { + "q": "I need the radius for a volume of 21.7931 and a height of 29.5106, please.", + "a": "0.48483699404495373", + "valid": true, + "kind": "compute", + "expect": 0.48483699404495373, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Cylinder)" + }, + { + "q": "If the volume is 21.7931 and the height is 29.5106, what is the radius?", + "a": "0.48483699404495373", + "valid": true, + "kind": "compute", + "expect": 0.48483699404495373, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Cylinder)" + }, + { + "q": "Could you work out the radius given volume = 153.15, height = 18.5953?", + "a": "1.6191300739110386", + "valid": true, + "kind": "compute", + "expect": 1.6191300739110386, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Cylinder)" + }, + { + "q": "I need the radius for a volume of 153.15 and a height of 18.5953, please.", + "a": "1.6191300739110386", + "valid": true, + "kind": "compute", + "expect": 1.6191300739110386, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Cylinder)" + }, + { + "q": "If the volume is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Could you work out the radius given volume = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given volume = -0.318734, height = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-10/program.py b/root/organs10/physics/specialists/solved-radius-10/program.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9e8d21f1832bc67df09972faa9bb420ef6237e --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-10/program.py @@ -0,0 +1,7 @@ +"""radius from volume, height (Cylinder) +The maths organ (systems.py): solved from the system V = q*r**2*h; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume, height): + return 0.564189583547757*height**(-0.5)*volume**0.5 diff --git a/root/organs10/physics/specialists/solved-radius-10/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-10/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-10/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-11/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-11/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-11/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-11/panel.json b/root/organs10/physics/specialists/solved-radius-11/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ffd91f28c836eb95b551ada8d32895bfb9f30516 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-11/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for solid angle 107.961 and area 59.4105?", + "a": "0.7418204937809788", + "valid": true, + "kind": "compute", + "expect": 0.7418204937809788, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 107.961 and area of 59.4105.", + "a": "0.7418204937809788", + "valid": true, + "kind": "compute", + "expect": 0.7418204937809788, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 169.527 and area 280.774?", + "a": "1.2869415720277586", + "valid": true, + "kind": "compute", + "expect": 1.2869415720277586, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 169.527 and area of 280.774.", + "a": "1.2869415720277586", + "valid": true, + "kind": "compute", + "expect": 1.2869415720277586, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 1.91195 and area 82.2401?", + "a": "6.558481154132354", + "valid": true, + "kind": "compute", + "expect": 6.558481154132354, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 1.91195 and area of 82.2401.", + "a": "6.558481154132354", + "valid": true, + "kind": "compute", + "expect": 6.558481154132354, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 1.64379 and area 252.709?", + "a": "12.398994932734404", + "valid": true, + "kind": "compute", + "expect": 12.398994932734404, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 1.64379 and area of 252.709.", + "a": "12.398994932734404", + "valid": true, + "kind": "compute", + "expect": 12.398994932734404, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 18.3169 and area 6.8386?", + "a": "0.6110235416380068", + "valid": true, + "kind": "compute", + "expect": 0.6110235416380068, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 18.3169 and area of 6.8386.", + "a": "0.6110235416380068", + "valid": true, + "kind": "compute", + "expect": 0.6110235416380068, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 156.502 and area 185.886?", + "a": "1.0898430968678325", + "valid": true, + "kind": "compute", + "expect": 1.0898430968678325, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Tell me the radius with solid angle of 156.502 and area of 185.886.", + "a": "1.0898430968678325", + "valid": true, + "kind": "compute", + "expect": 1.0898430968678325, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "What is the radius for solid angle 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the radius with solid angle of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with solid angle of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative solid angle: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the solid angle is 8.50728 and the area is 17.7888, what is the radius?", + "a": "1.446031081556708", + "valid": true, + "kind": "compute", + "expect": 1.446031081556708, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Could you work out the radius given solid angle = 8.50728, area = 17.7888?", + "a": "1.446031081556708", + "valid": true, + "kind": "compute", + "expect": 1.446031081556708, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "I need the radius for a solid angle of 8.24951 and an area of 0.634021, please.", + "a": "0.277228413051426", + "valid": true, + "kind": "compute", + "expect": 0.277228413051426, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "If the solid angle is 8.24951 and the area is 0.634021, what is the radius?", + "a": "0.277228413051426", + "valid": true, + "kind": "compute", + "expect": 0.277228413051426, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Could you work out the radius given solid angle = 0.318734, area = 9.56607?", + "a": "5.478385267128411", + "valid": true, + "kind": "compute", + "expect": 5.478385267128411, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "I need the radius for a solid angle of 0.318734 and an area of 9.56607, please.", + "a": "5.478385267128411", + "valid": true, + "kind": "compute", + "expect": 5.478385267128411, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "If the solid angle is 0.671697 and the area is 14.2496, what is the radius?", + "a": "4.605895711138291", + "valid": true, + "kind": "compute", + "expect": 4.605895711138291, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Could you work out the radius given solid angle = 0.671697, area = 14.2496?", + "a": "4.605895711138291", + "valid": true, + "kind": "compute", + "expect": 4.605895711138291, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "I need the radius for a solid angle of 21.7931 and an area of 29.5106, please.", + "a": "1.163668594759594", + "valid": true, + "kind": "compute", + "expect": 1.163668594759594, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "If the solid angle is 21.7931 and the area is 29.5106, what is the radius?", + "a": "1.163668594759594", + "valid": true, + "kind": "compute", + "expect": 1.163668594759594, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "Could you work out the radius given solid angle = 153.15, area = 18.5953?", + "a": "0.3484522909175213", + "valid": true, + "kind": "compute", + "expect": 0.3484522909175213, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "I need the radius for a solid angle of 153.15 and an area of 18.5953, please.", + "a": "0.3484522909175213", + "valid": true, + "kind": "compute", + "expect": 0.3484522909175213, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system solid angle (Wikidata Q208476))" + }, + { + "q": "If the solid angle is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the radius given solid angle = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given solid angle = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative solid angle: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-11/program.py b/root/organs10/physics/specialists/solved-radius-11/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0aeebca6a5086a07061588318b03b94169993303 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-11/program.py @@ -0,0 +1,7 @@ +"""radius from solid angle, area (solid angle (Wikidata Q208476)) +The maths organ (systems.py): solved from the system q0 = q1 / q2 **(2); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(solid_angle, area): + return 1.0*area**0.5*solid_angle**(-0.5) diff --git a/root/organs10/physics/specialists/solved-radius-11/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-11/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-11/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-12/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-12/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-12/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-12/panel.json b/root/organs10/physics/specialists/solved-radius-12/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..09de649f897db27501425c5408c6df88017d69fb --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-12/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for angular displacement 107.961 and arc length 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 107.961 and arc length of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 169.527 and arc length 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 169.527 and arc length of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 1.91195 and arc length 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 1.91195 and arc length of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 1.64379 and arc length 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 1.64379 and arc length of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 18.3169 and arc length 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 18.3169 and arc length of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 156.502 and arc length 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Tell me the radius with angular displacement of 156.502 and arc length of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "What is the radius for angular displacement 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the arc length is not given" + }, + { + "q": "Tell me the radius with angular displacement of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the arc length is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with angular displacement of -1.91195 and arc length of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular displacement: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the angular displacement is 8.50728 and the arc length is 17.7888, what is the radius?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Could you work out the radius given angular displacement = 8.50728, arc length = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "I need the radius for an angular displacement of 8.24951 and an arc length of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "If the angular displacement is 8.24951 and the arc length is 0.634021, what is the radius?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Could you work out the radius given angular displacement = 0.318734, arc length = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "I need the radius for an angular displacement of 0.318734 and an arc length of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "If the angular displacement is 0.671697 and the arc length is 14.2496, what is the radius?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Could you work out the radius given angular displacement = 0.671697, arc length = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "I need the radius for an angular displacement of 21.7931 and an arc length of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "If the angular displacement is 21.7931 and the arc length is 29.5106, what is the radius?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "Could you work out the radius given angular displacement = 153.15, arc length = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "I need the radius for an angular displacement of 153.15 and an arc length of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system angular displacement (Wikidata Q3305038))" + }, + { + "q": "If the angular displacement is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the arc length is not given" + }, + { + "q": "Could you work out the radius given angular displacement = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the arc length is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given angular displacement = -0.318734, arc length = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular displacement: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-12/program.py b/root/organs10/physics/specialists/solved-radius-12/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3a99646117f0f27c6cbdd8c5a90dda61ebc352 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-12/program.py @@ -0,0 +1,7 @@ +"""radius from angular displacement, arc length (angular displacement (Wikidata Q3305038)) +The maths organ (systems.py): solved from the system q0 = q1 / q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(angular_displacement, arc_length): + return 1.0*arc_length/angular_displacement diff --git a/root/organs10/physics/specialists/solved-radius-12/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-12/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-12/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-2/panel.json b/root/organs10/physics/specialists/solved-radius-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..4a782bf1be4294ab0533c9a8ad7ea5cd55509a22 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for area 107.961?", + "a": "5.86216233754748", + "valid": true, + "kind": "compute", + "expect": 5.86216233754748, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 107.961.", + "a": "5.86216233754748", + "valid": true, + "kind": "compute", + "expect": 5.86216233754748, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Circle)" + }, + { + "q": "What is the radius for area 6.34623?", + "a": "1.4212903810075577", + "valid": true, + "kind": "compute", + "expect": 1.4212903810075577, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 6.34623.", + "a": "1.4212903810075577", + "valid": true, + "kind": "compute", + "expect": 1.4212903810075577, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Circle)" + }, + { + "q": "What is the radius for area 0.551236?", + "a": "0.41888401874417486", + "valid": true, + "kind": "compute", + "expect": 0.41888401874417486, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 0.551236.", + "a": "0.41888401874417486", + "valid": true, + "kind": "compute", + "expect": 0.41888401874417486, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Circle)" + }, + { + "q": "What is the radius for area 186.27?", + "a": "7.700103940495607", + "valid": true, + "kind": "compute", + "expect": 7.700103940495607, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 186.27.", + "a": "7.700103940495607", + "valid": true, + "kind": "compute", + "expect": 7.700103940495607, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Circle)" + }, + { + "q": "What is the radius for area 0.710236?", + "a": "0.4754737041287415", + "valid": true, + "kind": "compute", + "expect": 0.4754737041287415, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 0.710236.", + "a": "0.4754737041287415", + "valid": true, + "kind": "compute", + "expect": 0.4754737041287415, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Circle)" + }, + { + "q": "What is the radius for area 79.8435?", + "a": "5.041327938047008", + "valid": true, + "kind": "compute", + "expect": 5.041327938047008, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Circle)" + }, + { + "q": "Tell me the radius with area of 79.8435.", + "a": "5.041327938047008", + "valid": true, + "kind": "compute", + "expect": 5.041327938047008, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Circle)" + }, + { + "q": "What is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the radius, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with area of -0.551236.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative area: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the area is 58.5346, what is the radius?", + "a": "4.316496269273659", + "valid": true, + "kind": "compute", + "expect": 4.316496269273659, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Circle)" + }, + { + "q": "Could you work out the radius given area = 58.5346?", + "a": "4.316496269273659", + "valid": true, + "kind": "compute", + "expect": 4.316496269273659, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Circle)" + }, + { + "q": "I need the radius for an area of 31.9492, please.", + "a": "3.1890025425522377", + "valid": true, + "kind": "compute", + "expect": 3.1890025425522377, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Circle)" + }, + { + "q": "If the area is 31.9492, what is the radius?", + "a": "3.1890025425522377", + "valid": true, + "kind": "compute", + "expect": 3.1890025425522377, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Circle)" + }, + { + "q": "Could you work out the radius given area = 6.8386?", + "a": "1.4753960046674068", + "valid": true, + "kind": "compute", + "expect": 1.4753960046674068, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Circle)" + }, + { + "q": "I need the radius for an area of 6.8386, please.", + "a": "1.4753960046674068", + "valid": true, + "kind": "compute", + "expect": 1.4753960046674068, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Circle)" + }, + { + "q": "If the area is 17.3414, what is the radius?", + "a": "2.349457426517296", + "valid": true, + "kind": "compute", + "expect": 2.349457426517296, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Circle)" + }, + { + "q": "Could you work out the radius given area = 17.3414?", + "a": "2.349457426517296", + "valid": true, + "kind": "compute", + "expect": 2.349457426517296, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Circle)" + }, + { + "q": "I need the radius for an area of 0.380269, please.", + "a": "0.34791267867449865", + "valid": true, + "kind": "compute", + "expect": 0.34791267867449865, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Circle)" + }, + { + "q": "If the area is 0.380269, what is the radius?", + "a": "0.34791267867449865", + "valid": true, + "kind": "compute", + "expect": 0.34791267867449865, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Circle)" + }, + { + "q": "Could you work out the radius given area = 291.545?", + "a": "9.633359922413222", + "valid": true, + "kind": "compute", + "expect": 9.633359922413222, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Circle)" + }, + { + "q": "I need the radius for an area of 291.545, please.", + "a": "9.633359922413222", + "valid": true, + "kind": "compute", + "expect": 9.633359922413222, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Circle)" + }, + { + "q": "I need the radius, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Can you tell me the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given area = -6.8386?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative area: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-2/program.py b/root/organs10/physics/specialists/solved-radius-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3df6b7cc48a7b4b23c59700747acb419290573c7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-2/program.py @@ -0,0 +1,7 @@ +"""radius from area (Circle) +The maths organ (systems.py): solved from the system c = 2*q*r; A = q*r**2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(area): + return 0.564189583547757*area**0.5 diff --git a/root/organs10/physics/specialists/solved-radius-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-3/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-3/panel.json b/root/organs10/physics/specialists/solved-radius-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..314c8555c5438cad0fd04016428a2224639dd4f9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for volume 107.961?", + "a": "2.953876373191259", + "valid": true, + "kind": "compute", + "expect": 2.953876373191259, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 107.961.", + "a": "2.953876373191259", + "valid": true, + "kind": "compute", + "expect": 2.953876373191259, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Sphere)" + }, + { + "q": "What is the radius for volume 6.34623?", + "a": "1.148529882100777", + "valid": true, + "kind": "compute", + "expect": 1.148529882100777, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 6.34623.", + "a": "1.148529882100777", + "valid": true, + "kind": "compute", + "expect": 1.148529882100777, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Sphere)" + }, + { + "q": "What is the radius for volume 0.551236?", + "a": "0.5086467596058601", + "valid": true, + "kind": "compute", + "expect": 0.5086467596058601, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 0.551236.", + "a": "0.5086467596058601", + "valid": true, + "kind": "compute", + "expect": 0.5086467596058601, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Sphere)" + }, + { + "q": "What is the radius for volume 186.27?", + "a": "3.542839511600505", + "valid": true, + "kind": "compute", + "expect": 3.542839511600505, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 186.27.", + "a": "3.542839511600505", + "valid": true, + "kind": "compute", + "expect": 3.542839511600505, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Sphere)" + }, + { + "q": "What is the radius for volume 0.710236?", + "a": "0.5534835996621714", + "valid": true, + "kind": "compute", + "expect": 0.5534835996621714, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 0.710236.", + "a": "0.5534835996621714", + "valid": true, + "kind": "compute", + "expect": 0.5534835996621714, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Sphere)" + }, + { + "q": "What is the radius for volume 79.8435?", + "a": "2.671265492310275", + "valid": true, + "kind": "compute", + "expect": 2.671265492310275, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Sphere)" + }, + { + "q": "Tell me the radius with volume of 79.8435.", + "a": "2.671265492310275", + "valid": true, + "kind": "compute", + "expect": 2.671265492310275, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Sphere)" + }, + { + "q": "What is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Could you work out the radius, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with volume of -0.551236.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume is 58.5346, what is the radius?", + "a": "2.4086553814263683", + "valid": true, + "kind": "compute", + "expect": 2.4086553814263683, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Sphere)" + }, + { + "q": "Could you work out the radius given volume = 58.5346?", + "a": "2.4086553814263683", + "valid": true, + "kind": "compute", + "expect": 2.4086553814263683, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Sphere)" + }, + { + "q": "I need the radius for a volume of 31.9492, please.", + "a": "1.9684467225958897", + "valid": true, + "kind": "compute", + "expect": 1.9684467225958897, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Sphere)" + }, + { + "q": "If the volume is 31.9492, what is the radius?", + "a": "1.9684467225958897", + "valid": true, + "kind": "compute", + "expect": 1.9684467225958897, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Sphere)" + }, + { + "q": "Could you work out the radius given volume = 6.8386?", + "a": "1.1774961338108154", + "valid": true, + "kind": "compute", + "expect": 1.1774961338108154, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Sphere)" + }, + { + "q": "I need the radius for a volume of 6.8386, please.", + "a": "1.1774961338108154", + "valid": true, + "kind": "compute", + "expect": 1.1774961338108154, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Sphere)" + }, + { + "q": "If the volume is 17.3414, what is the radius?", + "a": "1.605703944759535", + "valid": true, + "kind": "compute", + "expect": 1.605703944759535, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Sphere)" + }, + { + "q": "Could you work out the radius given volume = 17.3414?", + "a": "1.605703944759535", + "valid": true, + "kind": "compute", + "expect": 1.605703944759535, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Sphere)" + }, + { + "q": "I need the radius for a volume of 0.380269, please.", + "a": "0.4494353807303775", + "valid": true, + "kind": "compute", + "expect": 0.4494353807303775, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Sphere)" + }, + { + "q": "If the volume is 0.380269, what is the radius?", + "a": "0.4494353807303775", + "valid": true, + "kind": "compute", + "expect": 0.4494353807303775, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Sphere)" + }, + { + "q": "Could you work out the radius given volume = 291.545?", + "a": "4.113444218280815", + "valid": true, + "kind": "compute", + "expect": 4.113444218280815, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Sphere)" + }, + { + "q": "I need the radius for a volume of 291.545, please.", + "a": "4.113444218280815", + "valid": true, + "kind": "compute", + "expect": 4.113444218280815, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Sphere)" + }, + { + "q": "I need the radius, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Can you tell me the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the volume is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given volume = -6.8386?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-3/program.py b/root/organs10/physics/specialists/solved-radius-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5f54cc457a89e8cfd294ebf26007761f53f66fff --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-3/program.py @@ -0,0 +1,7 @@ +"""radius from volume (Sphere) +The maths organ (systems.py): solved from the system V = 4*q*r**3/3; S = 4*q*r**2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume): + return 0.620350490899399*volume**0.333333333333333 diff --git a/root/organs10/physics/specialists/solved-radius-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-3/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-4/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-4/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-4/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-4/panel.json b/root/organs10/physics/specialists/solved-radius-4/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..caeb6d52c78b32bf3ad9349763d7802330a9a3ba --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-4/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for surface area 107.961?", + "a": "2.931081168773735", + "valid": true, + "kind": "compute", + "expect": 2.931081168773735, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 107.961.", + "a": "2.931081168773735", + "valid": true, + "kind": "compute", + "expect": 2.931081168773735, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Sphere)" + }, + { + "q": "What is the radius for surface area 6.34623?", + "a": "0.7106451905037776", + "valid": true, + "kind": "compute", + "expect": 0.7106451905037776, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 6.34623.", + "a": "0.7106451905037776", + "valid": true, + "kind": "compute", + "expect": 0.7106451905037776, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Sphere)" + }, + { + "q": "What is the radius for surface area 0.551236?", + "a": "0.20944200937208707", + "valid": true, + "kind": "compute", + "expect": 0.20944200937208707, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 0.551236.", + "a": "0.20944200937208707", + "valid": true, + "kind": "compute", + "expect": 0.20944200937208707, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Sphere)" + }, + { + "q": "What is the radius for surface area 186.27?", + "a": "3.850051970247797", + "valid": true, + "kind": "compute", + "expect": 3.850051970247797, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 186.27.", + "a": "3.850051970247797", + "valid": true, + "kind": "compute", + "expect": 3.850051970247797, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Sphere)" + }, + { + "q": "What is the radius for surface area 0.710236?", + "a": "0.23773685206437034", + "valid": true, + "kind": "compute", + "expect": 0.23773685206437034, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 0.710236.", + "a": "0.23773685206437034", + "valid": true, + "kind": "compute", + "expect": 0.23773685206437034, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Sphere)" + }, + { + "q": "What is the radius for surface area 79.8435?", + "a": "2.520663969023499", + "valid": true, + "kind": "compute", + "expect": 2.520663969023499, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Sphere)" + }, + { + "q": "Tell me the radius with surface area of 79.8435.", + "a": "2.520663969023499", + "valid": true, + "kind": "compute", + "expect": 2.520663969023499, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Sphere)" + }, + { + "q": "What is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the surface area is not given" + }, + { + "q": "Could you work out the radius, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the surface area is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with surface area of -0.551236.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative surface area: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the surface area is 58.5346, what is the radius?", + "a": "2.1582481346368256", + "valid": true, + "kind": "compute", + "expect": 2.1582481346368256, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Sphere)" + }, + { + "q": "Could you work out the radius given surface area = 58.5346?", + "a": "2.1582481346368256", + "valid": true, + "kind": "compute", + "expect": 2.1582481346368256, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Sphere)" + }, + { + "q": "I need the radius for a surface area of 31.9492, please.", + "a": "1.5945012712761162", + "valid": true, + "kind": "compute", + "expect": 1.5945012712761162, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Sphere)" + }, + { + "q": "If the surface area is 31.9492, what is the radius?", + "a": "1.5945012712761162", + "valid": true, + "kind": "compute", + "expect": 1.5945012712761162, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Sphere)" + }, + { + "q": "Could you work out the radius given surface area = 6.8386?", + "a": "0.7376980023337021", + "valid": true, + "kind": "compute", + "expect": 0.7376980023337021, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Sphere)" + }, + { + "q": "I need the radius for a surface area of 6.8386, please.", + "a": "0.7376980023337021", + "valid": true, + "kind": "compute", + "expect": 0.7376980023337021, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Sphere)" + }, + { + "q": "If the surface area is 17.3414, what is the radius?", + "a": "1.1747287132586457", + "valid": true, + "kind": "compute", + "expect": 1.1747287132586457, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Sphere)" + }, + { + "q": "Could you work out the radius given surface area = 17.3414?", + "a": "1.1747287132586457", + "valid": true, + "kind": "compute", + "expect": 1.1747287132586457, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Sphere)" + }, + { + "q": "I need the radius for a surface area of 0.380269, please.", + "a": "0.17395633933724902", + "valid": true, + "kind": "compute", + "expect": 0.17395633933724902, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Sphere)" + }, + { + "q": "If the surface area is 0.380269, what is the radius?", + "a": "0.17395633933724902", + "valid": true, + "kind": "compute", + "expect": 0.17395633933724902, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Sphere)" + }, + { + "q": "Could you work out the radius given surface area = 291.545?", + "a": "4.816679961206602", + "valid": true, + "kind": "compute", + "expect": 4.816679961206602, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Sphere)" + }, + { + "q": "I need the radius for a surface area of 291.545, please.", + "a": "4.816679961206602", + "valid": true, + "kind": "compute", + "expect": 4.816679961206602, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Sphere)" + }, + { + "q": "I need the radius, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the surface area is not given" + }, + { + "q": "Can you tell me the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the surface area is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given surface area = -6.8386?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative surface area: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-4/program.py b/root/organs10/physics/specialists/solved-radius-4/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2094f2291d69a04bdcd93f20bbe8e3cf39cc69e8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-4/program.py @@ -0,0 +1,7 @@ +"""radius from surface area (Sphere) +The maths organ (systems.py): solved from the system V = 4*q*r**3/3; S = 4*q*r**2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(surface_area): + return 0.282094791773878*surface_area**0.5 diff --git a/root/organs10/physics/specialists/solved-radius-4/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-4/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-4/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-5/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-5/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-5/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-5/panel.json b/root/organs10/physics/specialists/solved-radius-5/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b21e48e039c4afcce3f9997b31026d8dd1bd897c --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-5/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for diameter 107.961?", + "a": "53.98033294498101", + "valid": true, + "kind": "compute", + "expect": 53.98033294498101, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 107.961.", + "a": "53.98033294498101", + "valid": true, + "kind": "compute", + "expect": 53.98033294498101, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Diameter)" + }, + { + "q": "What is the radius for diameter 22.652?", + "a": "11.326011398427896", + "valid": true, + "kind": "compute", + "expect": 11.326011398427896, + "dtype": "quantity", + "unit": "m", + "why": "radius for [22.652023] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 22.652.", + "a": "11.326011398427896", + "valid": true, + "kind": "compute", + "expect": 11.326011398427896, + "dtype": "quantity", + "unit": "m", + "why": "radius for [22.652023] (the system Diameter)" + }, + { + "q": "What is the radius for diameter 173.394?", + "a": "86.69681920265126", + "valid": true, + "kind": "compute", + "expect": 86.69681920265126, + "dtype": "quantity", + "unit": "m", + "why": "radius for [173.393638] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 173.394.", + "a": "86.69681920265126", + "valid": true, + "kind": "compute", + "expect": 86.69681920265126, + "dtype": "quantity", + "unit": "m", + "why": "radius for [173.393638] (the system Diameter)" + }, + { + "q": "What is the radius for diameter 126.709?", + "a": "63.354625900091186", + "valid": true, + "kind": "compute", + "expect": 63.354625900091186, + "dtype": "quantity", + "unit": "m", + "why": "radius for [126.709252] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 126.709.", + "a": "63.354625900091186", + "valid": true, + "kind": "compute", + "expect": 63.354625900091186, + "dtype": "quantity", + "unit": "m", + "why": "radius for [126.709252] (the system Diameter)" + }, + { + "q": "What is the radius for diameter 0.671697?", + "a": "0.33584859989709676", + "valid": true, + "kind": "compute", + "expect": 0.33584859989709676, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 0.671697.", + "a": "0.33584859989709676", + "valid": true, + "kind": "compute", + "expect": 0.33584859989709676, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697] (the system Diameter)" + }, + { + "q": "What is the radius for diameter 1.16997?", + "a": "0.5849840029889679", + "valid": true, + "kind": "compute", + "expect": 0.5849840029889679, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.169968] (the system Diameter)" + }, + { + "q": "Tell me the radius with diameter of 1.16997.", + "a": "0.5849840029889679", + "valid": true, + "kind": "compute", + "expect": 0.5849840029889679, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.169968] (the system Diameter)" + }, + { + "q": "What is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diameter is not given" + }, + { + "q": "Could you work out the radius, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diameter is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with diameter of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative diameter: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the diameter is 2.57003, what is the radius?", + "a": "1.2850149566518219", + "valid": true, + "kind": "compute", + "expect": 1.2850149566518219, + "dtype": "quantity", + "unit": "m", + "why": "radius for [2.57003] (the system Diameter)" + }, + { + "q": "Could you work out the radius given diameter = 2.57003?", + "a": "1.2850149566518219", + "valid": true, + "kind": "compute", + "expect": 1.2850149566518219, + "dtype": "quantity", + "unit": "m", + "why": "radius for [2.57003] (the system Diameter)" + }, + { + "q": "I need the radius for a diameter of 48.921, please.", + "a": "24.460495430005917", + "valid": true, + "kind": "compute", + "expect": 24.460495430005917, + "dtype": "quantity", + "unit": "m", + "why": "radius for [48.920991] (the system Diameter)" + }, + { + "q": "If the diameter is 48.921, what is the radius?", + "a": "24.460495430005917", + "valid": true, + "kind": "compute", + "expect": 24.460495430005917, + "dtype": "quantity", + "unit": "m", + "why": "radius for [48.920991] (the system Diameter)" + }, + { + "q": "Could you work out the radius given diameter = 0.348438?", + "a": "0.17421883481501524", + "valid": true, + "kind": "compute", + "expect": 0.17421883481501524, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.348438] (the system Diameter)" + }, + { + "q": "I need the radius for a diameter of 0.348438, please.", + "a": "0.17421883481501524", + "valid": true, + "kind": "compute", + "expect": 0.17421883481501524, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.348438] (the system Diameter)" + }, + { + "q": "If the diameter is 252.709, what is the radius?", + "a": "126.35451212476376", + "valid": true, + "kind": "compute", + "expect": 126.35451212476376, + "dtype": "quantity", + "unit": "m", + "why": "radius for [252.709024] (the system Diameter)" + }, + { + "q": "Could you work out the radius given diameter = 252.709?", + "a": "126.35451212476376", + "valid": true, + "kind": "compute", + "expect": 126.35451212476376, + "dtype": "quantity", + "unit": "m", + "why": "radius for [252.709024] (the system Diameter)" + }, + { + "q": "I need the radius for a diameter of 20.3966, please.", + "a": "10.19827898098172", + "valid": true, + "kind": "compute", + "expect": 10.19827898098172, + "dtype": "quantity", + "unit": "m", + "why": "radius for [20.396558] (the system Diameter)" + }, + { + "q": "If the diameter is 20.3966, what is the radius?", + "a": "10.19827898098172", + "valid": true, + "kind": "compute", + "expect": 10.19827898098172, + "dtype": "quantity", + "unit": "m", + "why": "radius for [20.396558] (the system Diameter)" + }, + { + "q": "Could you work out the radius given diameter = 134.993?", + "a": "67.496478790369", + "valid": true, + "kind": "compute", + "expect": 67.496478790369, + "dtype": "quantity", + "unit": "m", + "why": "radius for [134.992958] (the system Diameter)" + }, + { + "q": "I need the radius for a diameter of 134.993, please.", + "a": "67.496478790369", + "valid": true, + "kind": "compute", + "expect": 67.496478790369, + "dtype": "quantity", + "unit": "m", + "why": "radius for [134.992958] (the system Diameter)" + }, + { + "q": "I need the radius, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diameter is not given" + }, + { + "q": "Can you tell me the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diameter is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given diameter = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative diameter: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-5/program.py b/root/organs10/physics/specialists/solved-radius-5/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0f04350c43bf03d512d4e0ce2984dd92693742be --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-5/program.py @@ -0,0 +1,7 @@ +"""radius from diameter (Diameter) +The maths organ (systems.py): solved from the system D = 2*r; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(diameter): + return 0.5*diameter diff --git a/root/organs10/physics/specialists/solved-radius-5/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-5/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-5/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-6/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-6/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-6/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-6/panel.json b/root/organs10/physics/specialists/solved-radius-6/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0214013c358bd5a7e053db25d0b221974b336469 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-6/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for centripetal force 107.961, mass 59.4105 and speed 5.77717?", + "a": "18.366531129286077", + "valid": true, + "kind": "compute", + "expect": 18.366531129286077, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105, 5.777165] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 107.961, mass of 59.4105 and speed of 5.77717.", + "a": "18.366531129286077", + "valid": true, + "kind": "compute", + "expect": 18.366531129286077, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105, 5.777165] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 85.2416, mass 160.878 and speed 2.69428?", + "a": "13.700346754392312", + "valid": true, + "kind": "compute", + "expect": 13.700346754392312, + "dtype": "quantity", + "unit": "m", + "why": "radius for [85.241623, 160.878442, 2.69428] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 85.2416, mass of 160.878 and speed of 2.69428.", + "a": "13.700346754392312", + "valid": true, + "kind": "compute", + "expect": 13.700346754392312, + "dtype": "quantity", + "unit": "m", + "why": "radius for [85.241623, 160.878442, 2.69428] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 45.6157, mass 4.97131 and speed 94.305?", + "a": "969.22906762173", + "valid": true, + "kind": "compute", + "expect": 969.22906762173, + "dtype": "quantity", + "unit": "m", + "why": "radius for [45.61567, 4.971307, 94.305046] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 45.6157, mass of 4.97131 and speed of 94.305.", + "a": "969.22906762173", + "valid": true, + "kind": "compute", + "expect": 969.22906762173, + "dtype": "quantity", + "unit": "m", + "why": "radius for [45.61567, 4.971307, 94.305046] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 10.5638, mass 198.839 and speed 0.671697?", + "a": "8.492325283716148", + "valid": true, + "kind": "compute", + "expect": 8.492325283716148, + "dtype": "quantity", + "unit": "m", + "why": "radius for [10.563843, 198.838955, 0.671697] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 10.5638, mass of 198.839 and speed of 0.671697.", + "a": "8.492325283716148", + "valid": true, + "kind": "compute", + "expect": 8.492325283716148, + "dtype": "quantity", + "unit": "m", + "why": "radius for [10.563843, 198.838955, 0.671697] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 21.7931, mass 29.5106 and speed 8.50341?", + "a": "97.91395189115711", + "valid": true, + "kind": "compute", + "expect": 97.91395189115711, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609, 8.503407] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 21.7931, mass of 29.5106 and speed of 8.50341.", + "a": "97.91395189115711", + "valid": true, + "kind": "compute", + "expect": 97.91395189115711, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609, 8.503407] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 223.509, mass 17.3414 and speed 7.10705?", + "a": "3.9189439520265457", + "valid": true, + "kind": "compute", + "expect": 3.9189439520265457, + "dtype": "quantity", + "unit": "m", + "why": "radius for [223.508796, 17.341435, 7.107049] (the system Centripetal force)" + }, + { + "q": "Tell me the radius with centripetal force of 223.509, mass of 17.3414 and speed of 7.10705.", + "a": "3.9189439520265457", + "valid": true, + "kind": "compute", + "expect": 3.9189439520265457, + "dtype": "quantity", + "unit": "m", + "why": "radius for [223.508796, 17.341435, 7.107049] (the system Centripetal force)" + }, + { + "q": "What is the radius for centripetal force 107.961 and mass 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Tell me the radius with centripetal force of 85.2416 and mass of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with centripetal force of -45.6157, mass of 4.97131 and speed of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative centripetal force: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the centripetal force is 17.7888, mass is 167.625 and the speed is 10.3291, what is the radius?", + "a": "1005.3416429182549", + "valid": true, + "kind": "compute", + "expect": 1005.3416429182549, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.788778, 167.624948, 10.329054] (the system Centripetal force)" + }, + { + "q": "Could you work out the radius given centripetal force = 17.7888, mass = 167.625, speed = 10.3291?", + "a": "1005.3416429182549", + "valid": true, + "kind": "compute", + "expect": 1005.3416429182549, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.788778, 167.624948, 10.329054] (the system Centripetal force)" + }, + { + "q": "I need the radius for a centripetal force of 21.511, a mass of 173.394 and a speed of 251.084, please.", + "a": "508171.6653749755", + "valid": true, + "kind": "compute", + "expect": 508171.6653749755, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.511016, 173.393638, 251.084037] (the system Centripetal force)" + }, + { + "q": "If the centripetal force is 21.511, mass is 173.394 and the speed is 251.084, what is the radius?", + "a": "508171.6653749755", + "valid": true, + "kind": "compute", + "expect": 508171.6653749755, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.511016, 173.393638, 251.084037] (the system Centripetal force)" + }, + { + "q": "Could you work out the radius given centripetal force = 129.245, mass = 1.18359, speed = 15.9416?", + "a": "2.327298137242035", + "valid": true, + "kind": "compute", + "expect": 2.327298137242035, + "dtype": "quantity", + "unit": "m", + "why": "radius for [129.244984, 1.18359, 15.941612] (the system Centripetal force)" + }, + { + "q": "I need the radius for a centripetal force of 129.245, a mass of 1.18359 and a speed of 15.9416, please.", + "a": "2.327298137242035", + "valid": true, + "kind": "compute", + "expect": 2.327298137242035, + "dtype": "quantity", + "unit": "m", + "why": "radius for [129.244984, 1.18359, 15.941612] (the system Centripetal force)" + }, + { + "q": "If the centripetal force is 20.3966, mass is 18.3169 and the speed is 6.8386, what is the radius?", + "a": "41.997986179011534", + "valid": true, + "kind": "compute", + "expect": 41.997986179011534, + "dtype": "quantity", + "unit": "m", + "why": "radius for [20.396558, 18.316867, 6.838598] (the system Centripetal force)" + }, + { + "q": "Could you work out the radius given centripetal force = 20.3966, mass = 18.3169, speed = 6.8386?", + "a": "41.997986179011534", + "valid": true, + "kind": "compute", + "expect": 41.997986179011534, + "dtype": "quantity", + "unit": "m", + "why": "radius for [20.396558, 18.316867, 6.838598] (the system Centripetal force)" + }, + { + "q": "I need the radius for a centripetal force of 185.886, a mass of 13.2373 and a speed of 4.71941, please.", + "a": "1.5860933957447276", + "valid": true, + "kind": "compute", + "expect": 1.5860933957447276, + "dtype": "quantity", + "unit": "m", + "why": "radius for [185.886273, 13.237311, 4.719415] (the system Centripetal force)" + }, + { + "q": "If the centripetal force is 185.886, mass is 13.2373 and the speed is 4.71941, what is the radius?", + "a": "1.5860933957447276", + "valid": true, + "kind": "compute", + "expect": 1.5860933957447276, + "dtype": "quantity", + "unit": "m", + "why": "radius for [185.886273, 13.237311, 4.719415] (the system Centripetal force)" + }, + { + "q": "Could you work out the radius given centripetal force = 9.1061, mass = 24.5721, speed = 108.451?", + "a": "31737.657518771255", + "valid": true, + "kind": "compute", + "expect": 31737.657518771255, + "dtype": "quantity", + "unit": "m", + "why": "radius for [9.106104, 24.572086, 108.450792] (the system Centripetal force)" + }, + { + "q": "I need the radius for a centripetal force of 9.1061, a mass of 24.5721 and a speed of 108.451, please.", + "a": "31737.657518771255", + "valid": true, + "kind": "compute", + "expect": 31737.657518771255, + "dtype": "quantity", + "unit": "m", + "why": "radius for [9.106104, 24.572086, 108.450792] (the system Centripetal force)" + }, + { + "q": "If the centripetal force is 17.7888 and the mass is 167.625, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Could you work out the radius given centripetal force = 21.511, mass = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given centripetal force = -129.245, mass = 1.18359, speed = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative centripetal force: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-6/program.py b/root/organs10/physics/specialists/solved-radius-6/program.py new file mode 100644 index 0000000000000000000000000000000000000000..29e2beac0fd9fae431efb5d6c6ca6173dc59b6e1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-6/program.py @@ -0,0 +1,7 @@ +"""radius from centripetal force, mass, speed (Centripetal force) +The maths organ (systems.py): solved from the system F = m*v**2/r; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(centripetal_force, mass, speed): + return 1.0*mass*speed**2/centripetal_force diff --git a/root/organs10/physics/specialists/solved-radius-6/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-6/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-6/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-7/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-7/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-7/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-7/panel.json b/root/organs10/physics/specialists/solved-radius-7/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..acea902ccc96d7d9ba4f694780f8bd94c0866dab --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-7/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for escape speed 107.961 and body mass 59.4105?", + "a": "6.804055054131176e-13", + "valid": true, + "kind": "compute", + "expect": 6.804055054131176e-13, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 107.961 and body mass of 59.4105.", + "a": "6.804055054131176e-13", + "valid": true, + "kind": "compute", + "expect": 6.804055054131176e-13, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 169.527 and body mass 280.774?", + "a": "1.304111160603372e-12", + "valid": true, + "kind": "compute", + "expect": 1.304111160603372e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 169.527 and body mass of 280.774.", + "a": "1.304111160603372e-12", + "valid": true, + "kind": "compute", + "expect": 1.304111160603372e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 1.91195 and body mass 82.2401?", + "a": "3.003069187602033e-09", + "valid": true, + "kind": "compute", + "expect": 3.003069187602033e-09, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 1.91195 and body mass of 82.2401.", + "a": "3.003069187602033e-09", + "valid": true, + "kind": "compute", + "expect": 3.003069187602033e-09, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 1.64379 and body mass 252.709?", + "a": "1.2484205201457633e-08", + "valid": true, + "kind": "compute", + "expect": 1.2484205201457633e-08, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 1.64379 and body mass of 252.709.", + "a": "1.2484205201457633e-08", + "valid": true, + "kind": "compute", + "expect": 1.2484205201457633e-08, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 18.3169 and body mass 6.8386?", + "a": "2.7208237701053008e-12", + "valid": true, + "kind": "compute", + "expect": 2.7208237701053008e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 18.3169 and body mass of 6.8386.", + "a": "2.7208237701053008e-12", + "valid": true, + "kind": "compute", + "expect": 2.7208237701053008e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 156.502 and body mass 185.886?", + "a": "1.0130813271696716e-12", + "valid": true, + "kind": "compute", + "expect": 1.0130813271696716e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Escape speed)" + }, + { + "q": "Tell me the radius with escape speed of 156.502 and body mass of 185.886.", + "a": "1.0130813271696716e-12", + "valid": true, + "kind": "compute", + "expect": 1.0130813271696716e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Escape speed)" + }, + { + "q": "What is the radius for escape speed 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Tell me the radius with escape speed of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with escape speed of -1.91195 and body mass of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative escape speed: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the escape speed is 8.50728 and the body mass is 17.7888, what is the radius?", + "a": "3.280953783092207e-11", + "valid": true, + "kind": "compute", + "expect": 3.280953783092207e-11, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Escape speed)" + }, + { + "q": "Could you work out the radius given escape speed = 8.50728, body mass = 17.7888?", + "a": "3.280953783092207e-11", + "valid": true, + "kind": "compute", + "expect": 3.280953783092207e-11, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Escape speed)" + }, + { + "q": "I need the radius for an escape speed of 8.24951 and a body mass of 0.634021, please.", + "a": "1.243606693263642e-12", + "valid": true, + "kind": "compute", + "expect": 1.243606693263642e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Escape speed)" + }, + { + "q": "If the escape speed is 8.24951 and the body mass is 0.634021, what is the radius?", + "a": "1.243606693263642e-12", + "valid": true, + "kind": "compute", + "expect": 1.243606693263642e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Escape speed)" + }, + { + "q": "Could you work out the radius given escape speed = 0.318734, body mass = 9.56607?", + "a": "1.2569337939198787e-08", + "valid": true, + "kind": "compute", + "expect": 1.2569337939198787e-08, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Escape speed)" + }, + { + "q": "I need the radius for an escape speed of 0.318734 and a body mass of 9.56607, please.", + "a": "1.2569337939198787e-08", + "valid": true, + "kind": "compute", + "expect": 1.2569337939198787e-08, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Escape speed)" + }, + { + "q": "If the escape speed is 0.671697 and the body mass is 14.2496, what is the radius?", + "a": "4.215900786566765e-09", + "valid": true, + "kind": "compute", + "expect": 4.215900786566765e-09, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Escape speed)" + }, + { + "q": "Could you work out the radius given escape speed = 0.671697, body mass = 14.2496?", + "a": "4.215900786566765e-09", + "valid": true, + "kind": "compute", + "expect": 4.215900786566765e-09, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Escape speed)" + }, + { + "q": "I need the radius for an escape speed of 21.7931 and a body mass of 29.5106, please.", + "a": "8.294205799703822e-12", + "valid": true, + "kind": "compute", + "expect": 8.294205799703822e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Escape speed)" + }, + { + "q": "If the escape speed is 21.7931 and the body mass is 29.5106, what is the radius?", + "a": "8.294205799703822e-12", + "valid": true, + "kind": "compute", + "expect": 8.294205799703822e-12, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Escape speed)" + }, + { + "q": "Could you work out the radius given escape speed = 153.15, body mass = 18.5953?", + "a": "1.0582918835214576e-13", + "valid": true, + "kind": "compute", + "expect": 1.0582918835214576e-13, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Escape speed)" + }, + { + "q": "I need the radius for an escape speed of 153.15 and a body mass of 18.5953, please.", + "a": "1.0582918835214576e-13", + "valid": true, + "kind": "compute", + "expect": 1.0582918835214576e-13, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Escape speed)" + }, + { + "q": "If the escape speed is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Could you work out the radius given escape speed = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given escape speed = -0.318734, body mass = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative escape speed: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-7/program.py b/root/organs10/physics/specialists/solved-radius-7/program.py new file mode 100644 index 0000000000000000000000000000000000000000..892606361496b88fecbbc9de58017ab86e793279 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-7/program.py @@ -0,0 +1,7 @@ +"""radius from escape speed, body mass (Escape speed) +The maths organ (systems.py): solved from the system v = sqrt(2*G*M/r); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(escape_speed, body_mass): + return 1.33486e-10*body_mass/escape_speed**2 diff --git a/root/organs10/physics/specialists/solved-radius-7/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-7/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-7/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-8/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-8/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-8/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-8/panel.json b/root/organs10/physics/specialists/solved-radius-8/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..94cc095e664d5c2bcf3b4e0dc6f89aff2c4c5fd0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-8/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for surface gravity 107.961 and body mass 59.4105?", + "a": "6.060405573870294e-06", + "valid": true, + "kind": "compute", + "expect": 6.060405573870294e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 107.961 and body mass of 59.4105.", + "a": "6.060405573870294e-06", + "valid": true, + "kind": "compute", + "expect": 6.060405573870294e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 169.527 and body mass 280.774?", + "a": "1.0513847948052488e-05", + "valid": true, + "kind": "compute", + "expect": 1.0513847948052488e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 169.527 and body mass of 280.774.", + "a": "1.0513847948052488e-05", + "valid": true, + "kind": "compute", + "expect": 1.0513847948052488e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 1.91195 and body mass 82.2401?", + "a": "5.3580422859498744e-05", + "valid": true, + "kind": "compute", + "expect": 5.3580422859498744e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 1.91195 and body mass of 82.2401.", + "a": "5.3580422859498744e-05", + "valid": true, + "kind": "compute", + "expect": 5.3580422859498744e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 1.64379 and body mass 252.709?", + "a": "0.00010129531150822984", + "valid": true, + "kind": "compute", + "expect": 0.00010129531150822984, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 1.64379 and body mass of 252.709.", + "a": "0.00010129531150822984", + "valid": true, + "kind": "compute", + "expect": 0.00010129531150822984, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 18.3169 and body mass 6.8386?", + "a": "4.991841703691544e-06", + "valid": true, + "kind": "compute", + "expect": 4.991841703691544e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 18.3169 and body mass of 6.8386.", + "a": "4.991841703691544e-06", + "valid": true, + "kind": "compute", + "expect": 4.991841703691544e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 156.502 and body mass 185.886?", + "a": "8.903624575316678e-06", + "valid": true, + "kind": "compute", + "expect": 8.903624575316678e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Surface gravity)" + }, + { + "q": "Tell me the radius with surface gravity of 156.502 and body mass of 185.886.", + "a": "8.903624575316678e-06", + "valid": true, + "kind": "compute", + "expect": 8.903624575316678e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Surface gravity)" + }, + { + "q": "What is the radius for surface gravity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Tell me the radius with surface gravity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with surface gravity of -1.91195 and body mass of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative surface gravity: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the surface gravity is 8.50728 and the body mass is 17.7888, what is the radius?", + "a": "1.1813551796054021e-05", + "valid": true, + "kind": "compute", + "expect": 1.1813551796054021e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Surface gravity)" + }, + { + "q": "Could you work out the radius given surface gravity = 8.50728, body mass = 17.7888?", + "a": "1.1813551796054021e-05", + "valid": true, + "kind": "compute", + "expect": 1.1813551796054021e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Surface gravity)" + }, + { + "q": "I need the radius for a surface gravity of 8.24951 and a body mass of 0.634021, please.", + "a": "2.26485603158347e-06", + "valid": true, + "kind": "compute", + "expect": 2.26485603158347e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Surface gravity)" + }, + { + "q": "If the surface gravity is 8.24951 and the body mass is 0.634021, what is the radius?", + "a": "2.26485603158347e-06", + "valid": true, + "kind": "compute", + "expect": 2.26485603158347e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Surface gravity)" + }, + { + "q": "Could you work out the radius given surface gravity = 0.318734, body mass = 9.56607?", + "a": "4.475642946919788e-05", + "valid": true, + "kind": "compute", + "expect": 4.475642946919788e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Surface gravity)" + }, + { + "q": "I need the radius for a surface gravity of 0.318734 and a body mass of 9.56607, please.", + "a": "4.475642946919788e-05", + "valid": true, + "kind": "compute", + "expect": 4.475642946919788e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Surface gravity)" + }, + { + "q": "If the surface gravity is 0.671697 and the body mass is 14.2496, what is the radius?", + "a": "3.762850483972908e-05", + "valid": true, + "kind": "compute", + "expect": 3.762850483972908e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Surface gravity)" + }, + { + "q": "Could you work out the radius given surface gravity = 0.671697, body mass = 14.2496?", + "a": "3.762850483972908e-05", + "valid": true, + "kind": "compute", + "expect": 3.762850483972908e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Surface gravity)" + }, + { + "q": "I need the radius for a surface gravity of 21.7931 and a body mass of 29.5106, please.", + "a": "9.506752235805764e-06", + "valid": true, + "kind": "compute", + "expect": 9.506752235805764e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Surface gravity)" + }, + { + "q": "If the surface gravity is 21.7931 and the body mass is 29.5106, what is the radius?", + "a": "9.506752235805764e-06", + "valid": true, + "kind": "compute", + "expect": 9.506752235805764e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Surface gravity)" + }, + { + "q": "Could you work out the radius given surface gravity = 153.15, body mass = 18.5953?", + "a": "2.8467293958690675e-06", + "valid": true, + "kind": "compute", + "expect": 2.8467293958690675e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Surface gravity)" + }, + { + "q": "I need the radius for a surface gravity of 153.15 and a body mass of 18.5953, please.", + "a": "2.8467293958690675e-06", + "valid": true, + "kind": "compute", + "expect": 2.8467293958690675e-06, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Surface gravity)" + }, + { + "q": "If the surface gravity is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Could you work out the radius given surface gravity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the body mass is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given surface gravity = -0.318734, body mass = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative surface gravity: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-8/program.py b/root/organs10/physics/specialists/solved-radius-8/program.py new file mode 100644 index 0000000000000000000000000000000000000000..17054e16f18eaba6169a7b9d17038e8c0e6159df --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-8/program.py @@ -0,0 +1,7 @@ +"""radius from surface gravity, body mass (Surface gravity) +The maths organ (systems.py): solved from the system a = G*M/r**2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(surface_gravity, body_mass): + return 8.16963891490927e-6*body_mass**0.5*surface_gravity**(-0.5) diff --git a/root/organs10/physics/specialists/solved-radius-8/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-8/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-8/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-9/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-9/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-9/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-9/panel.json b/root/organs10/physics/specialists/solved-radius-9/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..502f7b04156d12184bc907af295d846da23eefa3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-9/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for volume 107.961 and height 59.4105?", + "a": "1.3173065883164412", + "valid": true, + "kind": "compute", + "expect": 1.3173065883164412, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 107.961 and height of 59.4105.", + "a": "1.3173065883164412", + "valid": true, + "kind": "compute", + "expect": 1.3173065883164412, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666, 59.4105] (the system Cone)" + }, + { + "q": "What is the radius for volume 169.527 and height 280.774?", + "a": "0.7593235349963201", + "valid": true, + "kind": "compute", + "expect": 0.7593235349963201, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 169.527 and height of 280.774.", + "a": "0.7593235349963201", + "valid": true, + "kind": "compute", + "expect": 0.7593235349963201, + "dtype": "quantity", + "unit": "m", + "why": "radius for [169.526958, 280.773702] (the system Cone)" + }, + { + "q": "What is the radius for volume 1.91195 and height 82.2401?", + "a": "0.14899867832815583", + "valid": true, + "kind": "compute", + "expect": 0.14899867832815583, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 1.91195 and height of 82.2401.", + "a": "0.14899867832815583", + "valid": true, + "kind": "compute", + "expect": 0.14899867832815583, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.911952, 82.240072] (the system Cone)" + }, + { + "q": "What is the radius for volume 1.64379 and height 252.709?", + "a": "0.07881324487244804", + "valid": true, + "kind": "compute", + "expect": 0.07881324487244804, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 1.64379 and height of 252.709.", + "a": "0.07881324487244804", + "valid": true, + "kind": "compute", + "expect": 0.07881324487244804, + "dtype": "quantity", + "unit": "m", + "why": "radius for [1.643795, 252.709024] (the system Cone)" + }, + { + "q": "What is the radius for volume 18.3169 and height 6.8386?", + "a": "1.5992919375678847", + "valid": true, + "kind": "compute", + "expect": 1.5992919375678847, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 18.3169 and height of 6.8386.", + "a": "1.5992919375678847", + "valid": true, + "kind": "compute", + "expect": 1.5992919375678847, + "dtype": "quantity", + "unit": "m", + "why": "radius for [18.316867, 6.838598] (the system Cone)" + }, + { + "q": "What is the radius for volume 156.502 and height 185.886?", + "a": "0.896647440915384", + "valid": true, + "kind": "compute", + "expect": 0.896647440915384, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Cone)" + }, + { + "q": "Tell me the radius with volume of 156.502 and height of 185.886.", + "a": "0.896647440915384", + "valid": true, + "kind": "compute", + "expect": 0.896647440915384, + "dtype": "quantity", + "unit": "m", + "why": "radius for [156.50181, 185.886273] (the system Cone)" + }, + { + "q": "What is the radius for volume 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Tell me the radius with volume of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with volume of -1.91195 and height of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume is 8.50728 and the height is 17.7888, what is the radius?", + "a": "0.6757842457672766", + "valid": true, + "kind": "compute", + "expect": 0.6757842457672766, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Cone)" + }, + { + "q": "Could you work out the radius given volume = 8.50728, height = 17.7888?", + "a": "0.6757842457672766", + "valid": true, + "kind": "compute", + "expect": 0.6757842457672766, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.507283, 17.788778] (the system Cone)" + }, + { + "q": "I need the radius for a volume of 8.24951 and a height of 0.634021, please.", + "a": "3.524909344788433", + "valid": true, + "kind": "compute", + "expect": 3.524909344788433, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Cone)" + }, + { + "q": "If the volume is 8.24951 and the height is 0.634021, what is the radius?", + "a": "3.524909344788433", + "valid": true, + "kind": "compute", + "expect": 3.524909344788433, + "dtype": "quantity", + "unit": "m", + "why": "radius for [8.24951, 0.634021] (the system Cone)" + }, + { + "q": "Could you work out the radius given volume = 0.318734, height = 9.56607?", + "a": "0.17837464438094505", + "valid": true, + "kind": "compute", + "expect": 0.17837464438094505, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Cone)" + }, + { + "q": "I need the radius for a volume of 0.318734 and a height of 9.56607, please.", + "a": "0.17837464438094505", + "valid": true, + "kind": "compute", + "expect": 0.17837464438094505, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.318734, 9.566071] (the system Cone)" + }, + { + "q": "If the volume is 0.671697 and the height is 14.2496, what is the radius?", + "a": "0.2121639492276595", + "valid": true, + "kind": "compute", + "expect": 0.2121639492276595, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Cone)" + }, + { + "q": "Could you work out the radius given volume = 0.671697, height = 14.2496?", + "a": "0.2121639492276595", + "valid": true, + "kind": "compute", + "expect": 0.2121639492276595, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.671697, 14.249569] (the system Cone)" + }, + { + "q": "I need the radius for a volume of 21.7931 and a height of 29.5106, please.", + "a": "0.8397623070748272", + "valid": true, + "kind": "compute", + "expect": 0.8397623070748272, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Cone)" + }, + { + "q": "If the volume is 21.7931 and the height is 29.5106, what is the radius?", + "a": "0.8397623070748272", + "valid": true, + "kind": "compute", + "expect": 0.8397623070748272, + "dtype": "quantity", + "unit": "m", + "why": "radius for [21.793126, 29.510609] (the system Cone)" + }, + { + "q": "Could you work out the radius given volume = 153.15, height = 18.5953?", + "a": "2.804415552076665", + "valid": true, + "kind": "compute", + "expect": 2.804415552076665, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Cone)" + }, + { + "q": "I need the radius for a volume of 153.15 and a height of 18.5953, please.", + "a": "2.804415552076665", + "valid": true, + "kind": "compute", + "expect": 2.804415552076665, + "dtype": "quantity", + "unit": "m", + "why": "radius for [153.149965, 18.595315] (the system Cone)" + }, + { + "q": "If the volume is 8.50728, what is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Could you work out the radius given volume = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the height is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given volume = -0.318734, height = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-9/program.py b/root/organs10/physics/specialists/solved-radius-9/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d85cb6690bcffe092cda656c7574cf8fd26d48 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-9/program.py @@ -0,0 +1,7 @@ +"""radius from volume, height (Cone) +The maths organ (systems.py): solved from the system V = q*r**2*h/3; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume, height): + return 0.977205023805839*height**(-0.5)*volume**0.5 diff --git a/root/organs10/physics/specialists/solved-radius-9/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-9/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-9/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius-of-curvature/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius-of-curvature/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-of-curvature/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius-of-curvature/panel.json b/root/organs10/physics/specialists/solved-radius-of-curvature/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d7f4823e0e2c1f0768e956a44cb613c63df7140c --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-of-curvature/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius of curvature for boundary layer thickness 107.961, Görtler number 59.4105, speed 5.77717 and kinematic viscosity 1.89126?", + "a": "3326.5896296446417", + "valid": true, + "kind": "compute", + "expect": 3326.5896296446417, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [107.960666, 59.4105, 5.777165, 1.891256] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 107.961, Görtler number of 59.4105, speed of 5.77717 and kinematic viscosity of 1.89126.", + "a": "3326.5896296446417", + "valid": true, + "kind": "compute", + "expect": 3326.5896296446417, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [107.960666, 59.4105, 5.777165, 1.891256] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 2.69428, Görtler number 48.921, speed 157.223 and kinematic viscosity 35.6412?", + "a": "0.1590244018207729", + "valid": true, + "kind": "compute", + "expect": 0.1590244018207729, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [2.69428, 48.920991, 157.22256, 35.641157] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 2.69428, Görtler number of 48.921, speed of 157.223 and kinematic viscosity of 35.6412.", + "a": "0.1590244018207729", + "valid": true, + "kind": "compute", + "expect": 0.1590244018207729, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [2.69428, 48.920991, 157.22256, 35.641157] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 0.318734, Görtler number 9.56607, speed 126.709 and kinematic viscosity 1.70503?", + "a": "1.9542025095956421", + "valid": true, + "kind": "compute", + "expect": 1.9542025095956421, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [0.318734, 9.566071, 126.709252, 1.705032] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 0.318734, Görtler number of 9.56607, speed of 126.709 and kinematic viscosity of 1.70503.", + "a": "1.9542025095956421", + "valid": true, + "kind": "compute", + "expect": 1.9542025095956421, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [0.318734, 9.566071, 126.709252, 1.705032] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 87.781, Görtler number 13.2084, speed 246.329 and kinematic viscosity 20.3966?", + "a": "565480.5033112998", + "valid": true, + "kind": "compute", + "expect": 565480.5033112998, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [87.781013, 13.208419, 246.329053, 20.396558] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 87.781, Görtler number of 13.2084, speed of 246.329 and kinematic viscosity of 20.3966.", + "a": "565480.5033112998", + "valid": true, + "kind": "compute", + "expect": 565480.5033112998, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [87.781013, 13.208419, 246.329053, 20.396558] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 156.502, Görtler number 185.886, speed 13.2373 and kinematic viscosity 4.71941?", + "a": "872.7436579742882", + "valid": true, + "kind": "compute", + "expect": 872.7436579742882, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [156.50181, 185.886273, 13.237311, 4.719415] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 156.502, Görtler number of 185.886, speed of 13.2373 and kinematic viscosity of 4.71941.", + "a": "872.7436579742882", + "valid": true, + "kind": "compute", + "expect": 872.7436579742882, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [156.50181, 185.886273, 13.237311, 4.719415] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 24.5721, Görtler number 108.451, speed 1.69476 and kinematic viscosity 49.4843?", + "a": "0.0014795819253108358", + "valid": true, + "kind": "compute", + "expect": 0.0014795819253108358, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [24.572086, 108.450792, 1.694755, 49.484326] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 24.5721, Görtler number of 108.451, speed of 1.69476 and kinematic viscosity of 49.4843.", + "a": "0.0014795819253108358", + "valid": true, + "kind": "compute", + "expect": 0.0014795819253108358, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [24.572086, 108.450792, 1.694755, 49.484326] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "What is the radius of curvature for boundary layer thickness 107.961, Görtler number 59.4105 and speed 5.77717?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of 2.69428, Görtler number of 48.921 and speed of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "What is the radius of curvature of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of curvature of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius of curvature with boundary layer thickness of -0.318734, Görtler number of 9.56607, speed of 126.709 and kinematic viscosity of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative boundary layer thickness: no example had one" + }, + { + "q": "Which radius of curvature is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the boundary layer thickness is 167.625, Görtler number is 10.3291, speed is 2.21571 and the kinematic viscosity is 58.5346, what is the radius of curvature?", + "a": "63.25526409870373", + "valid": true, + "kind": "compute", + "expect": 63.25526409870373, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [167.624948, 10.329054, 2.215713, 58.534594] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = 167.625, Görtler number = 10.3291, speed = 2.21571, kinematic viscosity = 58.5346?", + "a": "63.25526409870373", + "valid": true, + "kind": "compute", + "expect": 63.25526409870373, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [167.624948, 10.329054, 2.215713, 58.534594] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "I need the radius of curvature for a boundary layer thickness of 8.53158, a Görtler number of 124.718, a speed of 1.91195 and a kinematic viscosity of 82.2401, please.", + "a": "2.1578205392405692e-05", + "valid": true, + "kind": "compute", + "expect": 2.1578205392405692e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [8.531577, 124.718185, 1.911952, 82.240072] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "If the boundary layer thickness is 8.53158, Görtler number is 124.718, speed is 1.91195 and the kinematic viscosity is 82.2401, what is the radius of curvature?", + "a": "2.1578205392405692e-05", + "valid": true, + "kind": "compute", + "expect": 2.1578205392405692e-05, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [8.531577, 124.718185, 1.911952, 82.240072] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = 81.1967, Görtler number = 6.98086, speed = 0.551236, kinematic viscosity = 2.88512?", + "a": "401.0006514746843", + "valid": true, + "kind": "compute", + "expect": 401.0006514746843, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [81.196705, 6.980857, 0.551236, 2.88512] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "I need the radius of curvature for a boundary layer thickness of 81.1967, a Görtler number of 6.98086, a speed of 0.551236 and a kinematic viscosity of 2.88512, please.", + "a": "401.0006514746843", + "valid": true, + "kind": "compute", + "expect": 401.0006514746843, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [81.196705, 6.980857, 0.551236, 2.88512] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "If the boundary layer thickness is 1.16997, Görtler number is 1.14865, speed is 21.7931 and the kinematic viscosity is 29.5106, what is the radius of curvature?", + "a": "0.6619535761197417", + "valid": true, + "kind": "compute", + "expect": 0.6619535761197417, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [1.169968, 1.148652, 21.793126, 29.510609] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = 1.16997, Görtler number = 1.14865, speed = 21.7931, kinematic viscosity = 29.5106?", + "a": "0.6619535761197417", + "valid": true, + "kind": "compute", + "expect": 0.6619535761197417, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [1.169968, 1.148652, 21.793126, 29.510609] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "I need the radius of curvature for a boundary layer thickness of 223.509, a Görtler number of 17.3414, a speed of 7.10705 and a kinematic viscosity of 30.2507, please.", + "a": "2049.369000707443", + "valid": true, + "kind": "compute", + "expect": 2049.369000707443, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [223.508796, 17.341435, 7.107049, 30.250749] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "If the boundary layer thickness is 223.509, Görtler number is 17.3414, speed is 7.10705 and the kinematic viscosity is 30.2507, what is the radius of curvature?", + "a": "2049.369000707443", + "valid": true, + "kind": "compute", + "expect": 2049.369000707443, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [223.508796, 17.341435, 7.107049, 30.250749] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = 0.869111, Görtler number = 39.1753, speed = 0.432217, kinematic viscosity = 16.6571?", + "a": "2.8801210778957374e-07", + "valid": true, + "kind": "compute", + "expect": 2.8801210778957374e-07, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [0.869111, 39.175263, 0.432217, 16.657051] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "I need the radius of curvature for a boundary layer thickness of 0.869111, a Görtler number of 39.1753, a speed of 0.432217 and a kinematic viscosity of 16.6571, please.", + "a": "2.8801210778957374e-07", + "valid": true, + "kind": "compute", + "expect": 2.8801210778957374e-07, + "dtype": "quantity", + "unit": "m", + "why": "radius of curvature for [0.869111, 39.175263, 0.432217, 16.657051] (the system Görtler number (Wikidata Q102723670))" + }, + { + "q": "If the boundary layer thickness is 167.625, Görtler number is 10.3291 and the speed is 2.21571, what is the radius of curvature?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = 8.53158, Görtler number = 124.718, speed = 1.91195?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the kinematic viscosity is not given" + }, + { + "q": "Do you know the radius of curvature of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of curvature of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius of curvature given boundary layer thickness = -81.1967, Görtler number = 6.98086, speed = 0.551236, kinematic viscosity = 2.88512?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative boundary layer thickness: no example had one" + }, + { + "q": "What is a typical radius of curvature?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius-of-curvature/program.py b/root/organs10/physics/specialists/solved-radius-of-curvature/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd6c7275b1c576ce58ee0a28cf714ec2266d131 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-of-curvature/program.py @@ -0,0 +1,7 @@ +"""radius of curvature from boundary layer thickness, Görtler number, speed, kinematic viscosity (Görtler number (Wikidata Q102723670)) +The maths organ (systems.py): solved from the system q2 = ((q3*q0)/(q4))*sqrt(((q0)/(q1))); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(boundary_layer_thickness, g_rtler_number, speed, kinematic_viscosity): + return 1.0*boundary_layer_thickness**3*speed**2/(g_rtler_number**2*kinematic_viscosity**2) diff --git a/root/organs10/physics/specialists/solved-radius-of-curvature/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius-of-curvature/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius-of-curvature/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-radius/organ_formula_v2.py b/root/organs10/physics/specialists/solved-radius/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-radius/panel.json b/root/organs10/physics/specialists/solved-radius/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..06933a62b9911e27db544b5355359481da418f7d --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the radius for circumference 107.961?", + "a": "17.182473635879994", + "valid": true, + "kind": "compute", + "expect": 17.182473635879994, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 107.961.", + "a": "17.182473635879994", + "valid": true, + "kind": "compute", + "expect": 17.182473635879994, + "dtype": "quantity", + "unit": "m", + "why": "radius for [107.960666] (the system Circle)" + }, + { + "q": "What is the radius for circumference 6.34623?", + "a": "1.0100331735722998", + "valid": true, + "kind": "compute", + "expect": 1.0100331735722998, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 6.34623.", + "a": "1.0100331735722998", + "valid": true, + "kind": "compute", + "expect": 1.0100331735722998, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.346226] (the system Circle)" + }, + { + "q": "What is the radius for circumference 0.551236?", + "a": "0.08773191057963474", + "valid": true, + "kind": "compute", + "expect": 0.08773191057963474, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 0.551236.", + "a": "0.08773191057963474", + "valid": true, + "kind": "compute", + "expect": 0.08773191057963474, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.551236] (the system Circle)" + }, + { + "q": "What is the radius for circumference 186.27?", + "a": "29.645800347217865", + "valid": true, + "kind": "compute", + "expect": 29.645800347217865, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 186.27.", + "a": "29.645800347217865", + "valid": true, + "kind": "compute", + "expect": 29.645800347217865, + "dtype": "quantity", + "unit": "m", + "why": "radius for [186.270057] (the system Circle)" + }, + { + "q": "What is the radius for circumference 0.710236?", + "a": "0.11303762165895252", + "valid": true, + "kind": "compute", + "expect": 0.11303762165895252, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 0.710236.", + "a": "0.11303762165895252", + "valid": true, + "kind": "compute", + "expect": 0.11303762165895252, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.710236] (the system Circle)" + }, + { + "q": "What is the radius for circumference 79.8435?", + "a": "12.707493689466592", + "valid": true, + "kind": "compute", + "expect": 12.707493689466592, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Circle)" + }, + { + "q": "Tell me the radius with circumference of 79.8435.", + "a": "12.707493689466592", + "valid": true, + "kind": "compute", + "expect": 12.707493689466592, + "dtype": "quantity", + "unit": "m", + "why": "radius for [79.843538] (the system Circle)" + }, + { + "q": "What is the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the circumference is not given" + }, + { + "q": "Could you work out the radius, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the circumference is not given" + }, + { + "q": "What is the radius of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the radius of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the radius with circumference of -0.551236.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative circumference: no example had one" + }, + { + "q": "Which radius is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the circumference is 58.5346, what is the radius?", + "a": "9.316070021326667", + "valid": true, + "kind": "compute", + "expect": 9.316070021326667, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Circle)" + }, + { + "q": "Could you work out the radius given circumference = 58.5346?", + "a": "9.316070021326667", + "valid": true, + "kind": "compute", + "expect": 9.316070021326667, + "dtype": "quantity", + "unit": "m", + "why": "radius for [58.534594] (the system Circle)" + }, + { + "q": "I need the radius for a circumference of 31.9492, please.", + "a": "5.084868608202297", + "valid": true, + "kind": "compute", + "expect": 5.084868608202297, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Circle)" + }, + { + "q": "If the circumference is 31.9492, what is the radius?", + "a": "5.084868608202297", + "valid": true, + "kind": "compute", + "expect": 5.084868608202297, + "dtype": "quantity", + "unit": "m", + "why": "radius for [31.949172] (the system Circle)" + }, + { + "q": "Could you work out the radius given circumference = 6.8386?", + "a": "1.0883966852942686", + "valid": true, + "kind": "compute", + "expect": 1.0883966852942686, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Circle)" + }, + { + "q": "I need the radius for a circumference of 6.8386, please.", + "a": "1.0883966852942686", + "valid": true, + "kind": "compute", + "expect": 1.0883966852942686, + "dtype": "quantity", + "unit": "m", + "why": "radius for [6.838598] (the system Circle)" + }, + { + "q": "If the circumference is 17.3414, what is the radius?", + "a": "2.7599750995086247", + "valid": true, + "kind": "compute", + "expect": 2.7599750995086247, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Circle)" + }, + { + "q": "Could you work out the radius given circumference = 17.3414?", + "a": "2.7599750995086247", + "valid": true, + "kind": "compute", + "expect": 2.7599750995086247, + "dtype": "quantity", + "unit": "m", + "why": "radius for [17.341435] (the system Circle)" + }, + { + "q": "I need the radius for a circumference of 0.380269, please.", + "a": "0.06052161599123222", + "valid": true, + "kind": "compute", + "expect": 0.06052161599123222, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Circle)" + }, + { + "q": "If the circumference is 0.380269, what is the radius?", + "a": "0.06052161599123222", + "valid": true, + "kind": "compute", + "expect": 0.06052161599123222, + "dtype": "quantity", + "unit": "m", + "why": "radius for [0.380269] (the system Circle)" + }, + { + "q": "Could you work out the radius given circumference = 291.545?", + "a": "46.40081169737843", + "valid": true, + "kind": "compute", + "expect": 46.40081169737843, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Circle)" + }, + { + "q": "I need the radius for a circumference of 291.545, please.", + "a": "46.40081169737843", + "valid": true, + "kind": "compute", + "expect": 46.40081169737843, + "dtype": "quantity", + "unit": "m", + "why": "radius for [291.544898] (the system Circle)" + }, + { + "q": "I need the radius, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the circumference is not given" + }, + { + "q": "Can you tell me the radius?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the circumference is not given" + }, + { + "q": "Do you know the radius of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the radius of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the radius given circumference = -6.8386?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative circumference: no example had one" + }, + { + "q": "What is a typical radius?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-radius/program.py b/root/organs10/physics/specialists/solved-radius/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2868168fe63eeff7cb9965ba14f7ec95cd4a0b7e --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius/program.py @@ -0,0 +1,7 @@ +"""radius from circumference (Circle) +The maths organ (systems.py): solved from the system c = 2*q*r; A = q*r**2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(circumference): + return 0.159154943091895*circumference diff --git a/root/organs10/physics/specialists/solved-radius/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-radius/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-radius/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-rate/organ_formula_v2.py b/root/organs10/physics/specialists/solved-rate/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-rate/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-rate/panel.json b/root/organs10/physics/specialists/solved-rate/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..60508361070154948c02557cedf694f9d1b02c3d --- /dev/null +++ b/root/organs10/physics/specialists/solved-rate/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the rate for cost 107.961 and time 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [107.960666, 59.4105] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 107.961 and time of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [107.960666, 59.4105] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 169.527 and time 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [169.526958, 280.773702] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 169.527 and time of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [169.526958, 280.773702] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 1.91195 and time 82.2401?", + "a": "0.0232484203885924", + "valid": true, + "kind": "compute", + "expect": 0.0232484203885924, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [1.911952, 82.240072] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 1.91195 and time of 82.2401.", + "a": "0.0232484203885924", + "valid": true, + "kind": "compute", + "expect": 0.0232484203885924, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [1.911952, 82.240072] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 1.64379 and time 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [1.643795, 252.709024] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 1.64379 and time of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [1.643795, 252.709024] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 18.3169 and time 6.8386?", + "a": "2.678453516094291", + "valid": true, + "kind": "compute", + "expect": 2.678453516094291, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [18.316867, 6.838598] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 18.3169 and time of 6.8386.", + "a": "2.678453516094291", + "valid": true, + "kind": "compute", + "expect": 2.678453516094291, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [18.316867, 6.838598] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 156.502 and time 185.886?", + "a": "0.8419223616111586", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111586, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [156.50181, 185.886273] (the system Hourly cost)" + }, + { + "q": "Tell me the rate with cost of 156.502 and time of 185.886.", + "a": "0.8419223616111586", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111586, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [156.50181, 185.886273] (the system Hourly cost)" + }, + { + "q": "What is the rate for cost 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Tell me the rate with cost of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "What is the rate of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the rate of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the rate with cost of -1.91195 and time of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative cost: no example had one" + }, + { + "q": "Which rate is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the cost is 8.50728 and the time is 17.7888, what is the rate?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [8.507283, 17.788778] (the system Hourly cost)" + }, + { + "q": "Could you work out the rate given cost = 8.50728, time = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [8.507283, 17.788778] (the system Hourly cost)" + }, + { + "q": "I need the rate for a cost of 8.24951 and a time of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [8.24951, 0.634021] (the system Hourly cost)" + }, + { + "q": "If the cost is 8.24951 and the time is 0.634021, what is the rate?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [8.24951, 0.634021] (the system Hourly cost)" + }, + { + "q": "Could you work out the rate given cost = 0.318734, time = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [0.318734, 9.566071] (the system Hourly cost)" + }, + { + "q": "I need the rate for a cost of 0.318734 and a time of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [0.318734, 9.566071] (the system Hourly cost)" + }, + { + "q": "If the cost is 0.671697 and the time is 14.2496, what is the rate?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [0.671697, 14.249569] (the system Hourly cost)" + }, + { + "q": "Could you work out the rate given cost = 0.671697, time = 14.2496?", + "a": "0.047138070274372355", + "valid": true, + "kind": "compute", + "expect": 0.047138070274372355, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [0.671697, 14.249569] (the system Hourly cost)" + }, + { + "q": "I need the rate for a cost of 21.7931 and a time of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [21.793126, 29.510609] (the system Hourly cost)" + }, + { + "q": "If the cost is 21.7931 and the time is 29.5106, what is the rate?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [21.793126, 29.510609] (the system Hourly cost)" + }, + { + "q": "Could you work out the rate given cost = 153.15, time = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [153.149965, 18.595315] (the system Hourly cost)" + }, + { + "q": "I need the rate for a cost of 153.15 and a time of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "$/h", + "why": "rate for [153.149965, 18.595315] (the system Hourly cost)" + }, + { + "q": "If the cost is 8.50728, what is the rate?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Could you work out the rate given cost = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Do you know the rate of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the rate of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the rate given cost = -0.318734, time = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative cost: no example had one" + }, + { + "q": "What is a typical rate?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-rate/program.py b/root/organs10/physics/specialists/solved-rate/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c6ec5b2a15f4126b46f499f74636ed06bfef4bfe --- /dev/null +++ b/root/organs10/physics/specialists/solved-rate/program.py @@ -0,0 +1,7 @@ +"""rate from cost, time (Hourly cost) +The maths organ (systems.py): solved from the system C = r*t; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(cost, time): + return 1.0*cost/time diff --git a/root/organs10/physics/specialists/solved-rate/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-rate/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-rate/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-recessional-velocity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-recessional-velocity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-recessional-velocity/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-recessional-velocity/panel.json b/root/organs10/physics/specialists/solved-recessional-velocity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e10ac7b1bc4db372ed013253c7a1d3bdb064b79f --- /dev/null +++ b/root/organs10/physics/specialists/solved-recessional-velocity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the recessional velocity for Hubble's constant 107.961 and proper distance 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [107.960666, 59.4105] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 107.961 and proper distance of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [107.960666, 59.4105] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 169.527 and proper distance 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [169.526958, 280.773702] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 169.527 and proper distance of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [169.526958, 280.773702] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 1.91195 and proper distance 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [1.911952, 82.240072] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 1.91195 and proper distance of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [1.911952, 82.240072] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 1.64379 and proper distance 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [1.643795, 252.709024] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 1.64379 and proper distance of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [1.643795, 252.709024] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 18.3169 and proper distance 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [18.316867, 6.838598] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 18.3169 and proper distance of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [18.316867, 6.838598] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 156.502 and proper distance 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [156.50181, 185.886273] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 156.502 and proper distance of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [156.50181, 185.886273] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "What is the recessional velocity for Hubble's constant 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the proper distance is not given" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the proper distance is not given" + }, + { + "q": "What is the recessional velocity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the recessional velocity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the recessional velocity with Hubble's constant of -1.91195 and proper distance of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Hubble's constant: no example had one" + }, + { + "q": "Which recessional velocity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the Hubble's constant is 8.50728 and the proper distance is 17.7888, what is the recessional velocity?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [8.507283, 17.788778] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = 8.50728, proper distance = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [8.507283, 17.788778] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the recessional velocity for a Hubble's constant of 8.24951 and a proper distance of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [8.24951, 0.634021] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 8.24951 and the proper distance is 0.634021, what is the recessional velocity?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [8.24951, 0.634021] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = 0.318734, proper distance = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [0.318734, 9.566071] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the recessional velocity for a Hubble's constant of 0.318734 and a proper distance of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [0.318734, 9.566071] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 0.671697 and the proper distance is 14.2496, what is the recessional velocity?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [0.671697, 14.249569] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = 0.671697, proper distance = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [0.671697, 14.249569] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the recessional velocity for a Hubble's constant of 21.7931 and a proper distance of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [21.793126, 29.510609] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 21.7931 and the proper distance is 29.5106, what is the recessional velocity?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [21.793126, 29.510609] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = 153.15, proper distance = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [153.149965, 18.595315] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "I need the recessional velocity for a Hubble's constant of 153.15 and a proper distance of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m/s", + "why": "recessional velocity for [153.149965, 18.595315] (the system Hubble–Lemaître law (Wikidata Q179916))" + }, + { + "q": "If the Hubble's constant is 8.50728, what is the recessional velocity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the proper distance is not given" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the proper distance is not given" + }, + { + "q": "Do you know the recessional velocity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the recessional velocity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the recessional velocity given Hubble's constant = -0.318734, proper distance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Hubble's constant: no example had one" + }, + { + "q": "What is a typical recessional velocity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-recessional-velocity/program.py b/root/organs10/physics/specialists/solved-recessional-velocity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ab74c1171c1e6b7318351b7867d3f461a700d5d5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-recessional-velocity/program.py @@ -0,0 +1,7 @@ +"""recessional velocity from Hubble's constant, proper distance (Hubble–Lemaître law (Wikidata Q179916)) +The maths organ (systems.py): solved from the system q1 = q0*q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(hubble_s_constant, proper_distance): + return 1.0*hubble_s_constant*proper_distance diff --git a/root/organs10/physics/specialists/solved-recessional-velocity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-recessional-velocity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-recessional-velocity/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-redshift/organ_formula_v2.py b/root/organs10/physics/specialists/solved-redshift/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-redshift/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-redshift/panel.json b/root/organs10/physics/specialists/solved-redshift/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b8dc4c05dd3835b079bdb96ddca2766f9045143c --- /dev/null +++ b/root/organs10/physics/specialists/solved-redshift/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the redshift for wavelength 107.961 and wavelength difference 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [107.960666, 59.4105] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 107.961 and wavelength difference of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [107.960666, 59.4105] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 169.527 and wavelength difference 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [169.526958, 280.773702] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 169.527 and wavelength difference of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [169.526958, 280.773702] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 1.91195 and wavelength difference 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [1.911952, 82.240072] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 1.91195 and wavelength difference of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [1.911952, 82.240072] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 1.64379 and wavelength difference 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [1.643795, 252.709024] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 1.64379 and wavelength difference of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [1.643795, 252.709024] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 18.3169 and wavelength difference 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [18.316867, 6.838598] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 18.3169 and wavelength difference of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [18.316867, 6.838598] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 156.502 and wavelength difference 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [156.50181, 185.886273] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Tell me the redshift with wavelength of 156.502 and wavelength difference of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [156.50181, 185.886273] (the system redshift (Wikidata Q76250))" + }, + { + "q": "What is the redshift for wavelength 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the wavelength difference is not given" + }, + { + "q": "Tell me the redshift with wavelength of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the wavelength difference is not given" + }, + { + "q": "What is the redshift of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the redshift of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the redshift with wavelength of -1.91195 and wavelength difference of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative wavelength: no example had one" + }, + { + "q": "Which redshift is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the wavelength is 8.50728 and the wavelength difference is 17.7888, what is the redshift?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [8.507283, 17.788778] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Could you work out the redshift given wavelength = 8.50728, wavelength difference = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [8.507283, 17.788778] (the system redshift (Wikidata Q76250))" + }, + { + "q": "I need the redshift for a wavelength of 8.24951 and a wavelength difference of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [8.24951, 0.634021] (the system redshift (Wikidata Q76250))" + }, + { + "q": "If the wavelength is 8.24951 and the wavelength difference is 0.634021, what is the redshift?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [8.24951, 0.634021] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Could you work out the redshift given wavelength = 0.318734, wavelength difference = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [0.318734, 9.566071] (the system redshift (Wikidata Q76250))" + }, + { + "q": "I need the redshift for a wavelength of 0.318734 and a wavelength difference of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [0.318734, 9.566071] (the system redshift (Wikidata Q76250))" + }, + { + "q": "If the wavelength is 0.671697 and the wavelength difference is 14.2496, what is the redshift?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [0.671697, 14.249569] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Could you work out the redshift given wavelength = 0.671697, wavelength difference = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [0.671697, 14.249569] (the system redshift (Wikidata Q76250))" + }, + { + "q": "I need the redshift for a wavelength of 21.7931 and a wavelength difference of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [21.793126, 29.510609] (the system redshift (Wikidata Q76250))" + }, + { + "q": "If the wavelength is 21.7931 and the wavelength difference is 29.5106, what is the redshift?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [21.793126, 29.510609] (the system redshift (Wikidata Q76250))" + }, + { + "q": "Could you work out the redshift given wavelength = 153.15, wavelength difference = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [153.149965, 18.595315] (the system redshift (Wikidata Q76250))" + }, + { + "q": "I need the redshift for a wavelength of 153.15 and a wavelength difference of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "redshift for [153.149965, 18.595315] (the system redshift (Wikidata Q76250))" + }, + { + "q": "If the wavelength is 8.50728, what is the redshift?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the wavelength difference is not given" + }, + { + "q": "Could you work out the redshift given wavelength = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the wavelength difference is not given" + }, + { + "q": "Do you know the redshift of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the redshift of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the redshift given wavelength = -0.318734, wavelength difference = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative wavelength: no example had one" + }, + { + "q": "What is a typical redshift?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-redshift/program.py b/root/organs10/physics/specialists/solved-redshift/program.py new file mode 100644 index 0000000000000000000000000000000000000000..37f2f96632f98fe3c6e39234091ffc76d88cc6b0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-redshift/program.py @@ -0,0 +1,7 @@ +"""redshift from wavelength, wavelength difference (redshift (Wikidata Q76250)) +The maths organ (systems.py): solved from the system q2 = ((q1)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(wavelength, wavelength_difference): + return 1.0*wavelength_difference/wavelength diff --git a/root/organs10/physics/specialists/solved-redshift/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-redshift/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-redshift/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reech-number/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reech-number/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reech-number/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reech-number/panel.json b/root/organs10/physics/specialists/solved-reech-number/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f21137a83bacc5ea5d9ca6c8e6d6ff7606c9aeaa --- /dev/null +++ b/root/organs10/physics/specialists/solved-reech-number/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Reech number for acceleration of free fall 107.961, characteristic length 59.4105 and speed relative to water 5.77717?", + "a": "13.862757914193818", + "valid": true, + "kind": "compute", + "expect": 13.862757914193818, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [107.960666, 59.4105, 5.777165] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 107.961, characteristic length of 59.4105 and speed relative to water of 5.77717.", + "a": "13.862757914193818", + "valid": true, + "kind": "compute", + "expect": 13.862757914193818, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [107.960666, 59.4105, 5.777165] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 85.2416, characteristic length 160.878 and speed relative to water 2.69428?", + "a": "43.46423815703506", + "valid": true, + "kind": "compute", + "expect": 43.46423815703506, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [85.241623, 160.878442, 2.69428] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 85.2416, characteristic length of 160.878 and speed relative to water of 2.69428.", + "a": "43.46423815703506", + "valid": true, + "kind": "compute", + "expect": 43.46423815703506, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [85.241623, 160.878442, 2.69428] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 45.6157, characteristic length 4.97131 and speed relative to water 94.305?", + "a": "0.15968253241393524", + "valid": true, + "kind": "compute", + "expect": 0.15968253241393524, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [45.61567, 4.971307, 94.305046] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 45.6157, characteristic length of 4.97131 and speed relative to water of 94.305.", + "a": "0.15968253241393524", + "valid": true, + "kind": "compute", + "expect": 0.15968253241393524, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [45.61567, 4.971307, 94.305046] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 10.5638, characteristic length 198.839 and speed relative to water 0.671697?", + "a": "68.23200957206197", + "valid": true, + "kind": "compute", + "expect": 68.23200957206197, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [10.563843, 198.838955, 0.671697] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 10.5638, characteristic length of 198.839 and speed relative to water of 0.671697.", + "a": "68.23200957206197", + "valid": true, + "kind": "compute", + "expect": 68.23200957206197, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [10.563843, 198.838955, 0.671697] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 21.7931, characteristic length 29.5106 and speed relative to water 8.50341?", + "a": "2.9823312363732577", + "valid": true, + "kind": "compute", + "expect": 2.9823312363732577, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [21.793126, 29.510609, 8.503407] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 21.7931, characteristic length of 29.5106 and speed relative to water of 8.50341.", + "a": "2.9823312363732577", + "valid": true, + "kind": "compute", + "expect": 2.9823312363732577, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [21.793126, 29.510609, 8.503407] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 223.509, characteristic length 17.3414 and speed relative to water 7.10705?", + "a": "8.759927384062154", + "valid": true, + "kind": "compute", + "expect": 8.759927384062154, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [223.508796, 17.341435, 7.107049] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 223.509, characteristic length of 17.3414 and speed relative to water of 7.10705.", + "a": "8.759927384062154", + "valid": true, + "kind": "compute", + "expect": 8.759927384062154, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [223.508796, 17.341435, 7.107049] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "What is the Reech number for acceleration of free fall 107.961 and characteristic length 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed relative to water is not given" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of 85.2416 and characteristic length of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed relative to water is not given" + }, + { + "q": "What is the Reech number of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the Reech number of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the Reech number with acceleration of free fall of -45.6157, characteristic length of 4.97131 and speed relative to water of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative acceleration of free fall: no example had one" + }, + { + "q": "Which Reech number is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the acceleration of free fall is 17.7888, characteristic length is 167.625 and the speed relative to water is 10.3291, what is the Reech number?", + "a": "5.286665342992554", + "valid": true, + "kind": "compute", + "expect": 5.286665342992554, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [17.788778, 167.624948, 10.329054] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = 17.7888, characteristic length = 167.625, speed relative to water = 10.3291?", + "a": "5.286665342992554", + "valid": true, + "kind": "compute", + "expect": 5.286665342992554, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [17.788778, 167.624948, 10.329054] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "I need the Reech number for an acceleration of free fall of 21.511, a characteristic length of 173.394 and a speed relative to water of 251.084, please.", + "a": "0.2432360469648453", + "valid": true, + "kind": "compute", + "expect": 0.2432360469648453, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [21.511016, 173.393638, 251.084037] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "If the acceleration of free fall is 21.511, characteristic length is 173.394 and the speed relative to water is 251.084, what is the Reech number?", + "a": "0.2432360469648453", + "valid": true, + "kind": "compute", + "expect": 0.2432360469648453, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [21.511016, 173.393638, 251.084037] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = 129.245, characteristic length = 1.18359, speed relative to water = 15.9416?", + "a": "0.7758455322295557", + "valid": true, + "kind": "compute", + "expect": 0.7758455322295557, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [129.244984, 1.18359, 15.941612] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "I need the Reech number for an acceleration of free fall of 129.245, a characteristic length of 1.18359 and a speed relative to water of 15.9416, please.", + "a": "0.7758455322295557", + "valid": true, + "kind": "compute", + "expect": 0.7758455322295557, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [129.244984, 1.18359, 15.941612] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "If the acceleration of free fall is 20.3966, characteristic length is 18.3169 and the speed relative to water is 6.8386, what is the Reech number?", + "a": "2.82642170403864", + "valid": true, + "kind": "compute", + "expect": 2.82642170403864, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [20.396558, 18.316867, 6.838598] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = 20.3966, characteristic length = 18.3169, speed relative to water = 6.8386?", + "a": "2.82642170403864", + "valid": true, + "kind": "compute", + "expect": 2.82642170403864, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [20.396558, 18.316867, 6.838598] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "I need the Reech number for an acceleration of free fall of 185.886, a characteristic length of 13.2373 and a speed relative to water of 4.71941, please.", + "a": "10.510790901460334", + "valid": true, + "kind": "compute", + "expect": 10.510790901460334, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [185.886273, 13.237311, 4.719415] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "If the acceleration of free fall is 185.886, characteristic length is 13.2373 and the speed relative to water is 4.71941, what is the Reech number?", + "a": "10.510790901460334", + "valid": true, + "kind": "compute", + "expect": 10.510790901460334, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [185.886273, 13.237311, 4.719415] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = 9.1061, characteristic length = 24.5721, speed relative to water = 108.451?", + "a": "0.1379286820953128", + "valid": true, + "kind": "compute", + "expect": 0.1379286820953128, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [9.106104, 24.572086, 108.450792] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "I need the Reech number for an acceleration of free fall of 9.1061, a characteristic length of 24.5721 and a speed relative to water of 108.451, please.", + "a": "0.1379286820953128", + "valid": true, + "kind": "compute", + "expect": 0.1379286820953128, + "dtype": "quantity", + "unit": "1", + "why": "Reech number for [9.106104, 24.572086, 108.450792] (the system Reech number (Wikidata Q25401602))" + }, + { + "q": "If the acceleration of free fall is 17.7888 and the characteristic length is 167.625, what is the Reech number?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed relative to water is not given" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = 21.511, characteristic length = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed relative to water is not given" + }, + { + "q": "Do you know the Reech number of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the Reech number of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the Reech number given acceleration of free fall = -129.245, characteristic length = 1.18359, speed relative to water = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative acceleration of free fall: no example had one" + }, + { + "q": "What is a typical Reech number?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reech-number/program.py b/root/organs10/physics/specialists/solved-reech-number/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5bba057ac8d0f48f99141b47e73bb69dbb7e59ae --- /dev/null +++ b/root/organs10/physics/specialists/solved-reech-number/program.py @@ -0,0 +1,7 @@ +"""Reech number from acceleration of free fall, characteristic length, speed relative to water (Reech number (Wikidata Q25401602)) +The maths organ (systems.py): solved from the system q0 = ((sqrt(q1*q2))/(q3)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(acceleration_of_free_fall, characteristic_length, speed_relative_to_water): + return 1.0*acceleration_of_free_fall**0.5*characteristic_length**0.5/speed_relative_to_water diff --git a/root/organs10/physics/specialists/solved-reech-number/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reech-number/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reech-number/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reference-density/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reference-density/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-density/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reference-density/panel.json b/root/organs10/physics/specialists/solved-reference-density/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..480581aa4170d99d543476af04324db4bcfad197 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-density/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reference density for relative density 107.961 and mass density 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [107.960666, 59.4105] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 107.961 and mass density of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [107.960666, 59.4105] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 169.527 and mass density 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [169.526958, 280.773702] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 169.527 and mass density of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [169.526958, 280.773702] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 1.91195 and mass density 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [1.911952, 82.240072] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 1.91195 and mass density of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [1.911952, 82.240072] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 1.64379 and mass density 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [1.643795, 252.709024] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 1.64379 and mass density of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [1.643795, 252.709024] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 18.3169 and mass density 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [18.316867, 6.838598] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 18.3169 and mass density of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [18.316867, 6.838598] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 156.502 and mass density 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [156.50181, 185.886273] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the reference density with relative density of 156.502 and mass density of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [156.50181, 185.886273] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the reference density for relative density 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Tell me the reference density with relative density of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "What is the reference density of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reference density of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reference density with relative density of -1.91195 and mass density of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relative density: no example had one" + }, + { + "q": "Which reference density is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the relative density is 8.50728 and the mass density is 17.7888, what is the reference density?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [8.507283, 17.788778] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the reference density given relative density = 8.50728, mass density = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [8.507283, 17.788778] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the reference density for a relative density of 8.24951 and a mass density of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [8.24951, 0.634021] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the relative density is 8.24951 and the mass density is 0.634021, what is the reference density?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [8.24951, 0.634021] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the reference density given relative density = 0.318734, mass density = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [0.318734, 9.566071] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the reference density for a relative density of 0.318734 and a mass density of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [0.318734, 9.566071] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the relative density is 0.671697 and the mass density is 14.2496, what is the reference density?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [0.671697, 14.249569] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the reference density given relative density = 0.671697, mass density = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [0.671697, 14.249569] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the reference density for a relative density of 21.7931 and a mass density of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [21.793126, 29.510609] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the relative density is 21.7931 and the mass density is 29.5106, what is the reference density?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [21.793126, 29.510609] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the reference density given relative density = 153.15, mass density = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [153.149965, 18.595315] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the reference density for a relative density of 153.15 and a mass density of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "kg/m^3", + "why": "reference density for [153.149965, 18.595315] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the relative density is 8.50728, what is the reference density?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Could you work out the reference density given relative density = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Do you know the reference density of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reference density of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reference density given relative density = -0.318734, mass density = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relative density: no example had one" + }, + { + "q": "What is a typical reference density?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reference-density/program.py b/root/organs10/physics/specialists/solved-reference-density/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb06219d3aa571ecf4433e90554a3d1151685ea --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-density/program.py @@ -0,0 +1,7 @@ +"""reference density from relative density, mass density (relative density (Wikidata Q11027905)) +The maths organ (systems.py): solved from the system q1 = q2 / q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(relative_density, mass_density): + return 1.0*mass_density/relative_density diff --git a/root/organs10/physics/specialists/solved-reference-density/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reference-density/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-density/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reference-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reference-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-energy/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reference-energy/panel.json b/root/organs10/physics/specialists/solved-reference-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..fc316555da3c4120dff27892f8fe4d0101940734 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reference energy for lethargy 8.50728 and neutron kinetic energy 17.7888?", + "a": "88066.76247008644", + "valid": true, + "kind": "compute", + "expect": 88066.76247008644, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [8.507283, 17.788778] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 8.50728 and neutron kinetic energy of 17.7888.", + "a": "88066.76247008644", + "valid": true, + "kind": "compute", + "expect": 88066.76247008644, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [8.507283, 17.788778] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 1.91195 and neutron kinetic energy 82.2401?", + "a": "556.4595258636808", + "valid": true, + "kind": "compute", + "expect": 556.4595258636808, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [1.911952, 82.240072] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 1.91195 and neutron kinetic energy of 82.2401.", + "a": "556.4595258636808", + "valid": true, + "kind": "compute", + "expect": 556.4595258636808, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [1.911952, 82.240072] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 1.64379 and neutron kinetic energy 252.709?", + "a": "1307.7118635379584", + "valid": true, + "kind": "compute", + "expect": 1307.7118635379584, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [1.643795, 252.709024] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 1.64379 and neutron kinetic energy of 252.709.", + "a": "1307.7118635379584", + "valid": true, + "kind": "compute", + "expect": 1307.7118635379584, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [1.643795, 252.709024] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 18.3169 and neutron kinetic energy 6.8386?", + "a": "616426573.708138", + "valid": true, + "kind": "compute", + "expect": 616426573.708138, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [18.316867, 6.838598] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 18.3169 and neutron kinetic energy of 6.8386.", + "a": "616426573.708138", + "valid": true, + "kind": "compute", + "expect": 616426573.708138, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [18.316867, 6.838598] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 0.710236 and neutron kinetic energy 1.45005?", + "a": "2.95007683101668", + "valid": true, + "kind": "compute", + "expect": 2.95007683101668, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.710236, 1.450045] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 0.710236 and neutron kinetic energy of 1.45005.", + "a": "2.95007683101668", + "valid": true, + "kind": "compute", + "expect": 2.95007683101668, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.710236, 1.450045] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 16.8989 and neutron kinetic energy 4.71659?", + "a": "102975555.74523023", + "valid": true, + "kind": "compute", + "expect": 102975555.74523023, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [16.898916, 4.716591] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the reference energy with lethargy of 16.8989 and neutron kinetic energy of 4.71659.", + "a": "102975555.74523023", + "valid": true, + "kind": "compute", + "expect": 102975555.74523023, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [16.898916, 4.716591] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the reference energy for lethargy 8.50728?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the neutron kinetic energy is not given" + }, + { + "q": "Tell me the reference energy with lethargy of 1.91195.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the neutron kinetic energy is not given" + }, + { + "q": "What is the reference energy of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reference energy of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reference energy with lethargy of -1.64379 and neutron kinetic energy of 252.709.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative lethargy: no example had one" + }, + { + "q": "Which reference energy is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the lethargy is 8.24951 and the neutron kinetic energy is 0.634021, what is the reference energy?", + "a": "2425.6058878506115", + "valid": true, + "kind": "compute", + "expect": 2425.6058878506115, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [8.24951, 0.634021] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the reference energy given lethargy = 8.24951, neutron kinetic energy = 0.634021?", + "a": "2425.6058878506115", + "valid": true, + "kind": "compute", + "expect": 2425.6058878506115, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [8.24951, 0.634021] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the reference energy for a lethargy of 0.318734 and a neutron kinetic energy of 9.56607, please.", + "a": "13.157035227066514", + "valid": true, + "kind": "compute", + "expect": 13.157035227066514, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.318734, 9.566071] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the lethargy is 0.318734 and the neutron kinetic energy is 9.56607, what is the reference energy?", + "a": "13.157035227066514", + "valid": true, + "kind": "compute", + "expect": 13.157035227066514, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.318734, 9.566071] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the reference energy given lethargy = 0.671697, neutron kinetic energy = 14.2496?", + "a": "27.894342280242007", + "valid": true, + "kind": "compute", + "expect": 27.894342280242007, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.671697, 14.249569] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the reference energy for a lethargy of 0.671697 and a neutron kinetic energy of 14.2496, please.", + "a": "27.894342280242007", + "valid": true, + "kind": "compute", + "expect": 27.894342280242007, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.671697, 14.249569] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the lethargy is 21.7931 and the neutron kinetic energy is 29.5106, what is the reference energy?", + "a": "86022635888.71588", + "valid": true, + "kind": "compute", + "expect": 86022635888.71588, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [21.793126, 29.510609] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the reference energy given lethargy = 21.7931, neutron kinetic energy = 29.5106?", + "a": "86022635888.71588", + "valid": true, + "kind": "compute", + "expect": 86022635888.71588, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [21.793126, 29.510609] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the reference energy for a lethargy of 0.432217 and a neutron kinetic energy of 16.6571, please.", + "a": "25.66301770770792", + "valid": true, + "kind": "compute", + "expect": 25.66301770770792, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.432217, 16.657051] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the lethargy is 0.432217 and the neutron kinetic energy is 16.6571, what is the reference energy?", + "a": "25.66301770770792", + "valid": true, + "kind": "compute", + "expect": 25.66301770770792, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.432217, 16.657051] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the reference energy given lethargy = 0.744193, neutron kinetic energy = 1.35435?", + "a": "2.850548128444535", + "valid": true, + "kind": "compute", + "expect": 2.850548128444535, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.744193, 1.354346] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the reference energy for a lethargy of 0.744193 and a neutron kinetic energy of 1.35435, please.", + "a": "2.850548128444535", + "valid": true, + "kind": "compute", + "expect": 2.850548128444535, + "dtype": "quantity", + "unit": "J", + "why": "reference energy for [0.744193, 1.354346] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the lethargy is 8.24951, what is the reference energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the neutron kinetic energy is not given" + }, + { + "q": "Could you work out the reference energy given lethargy = 0.318734?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the neutron kinetic energy is not given" + }, + { + "q": "Do you know the reference energy of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reference energy of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reference energy given lethargy = -0.671697, neutron kinetic energy = 14.2496?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative lethargy: no example had one" + }, + { + "q": "What is a typical reference energy?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reference-energy/program.py b/root/organs10/physics/specialists/solved-reference-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..408c23ecf1d75d74381943f9608575e35add87bf --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-energy/program.py @@ -0,0 +1,7 @@ +"""reference energy from lethargy, neutron kinetic energy (lethargy (Wikidata Q25508781)) +The maths organ (systems.py): solved from the system q1 = log (((q0)/(q2))); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(lethargy, neutron_kinetic_energy): + return 1.0*neutron_kinetic_energy*math.exp(1.0*lethargy) diff --git a/root/organs10/physics/specialists/solved-reference-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reference-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-energy/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reference-temperature/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reference-temperature/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-temperature/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reference-temperature/panel.json b/root/organs10/physics/specialists/solved-reference-temperature/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3ebfa861a0dafef18367756e61fe616375636285 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-temperature/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reference temperature for temperature difference 8.50728 and thermodynamic temperature 17.7888?", + "a": "9.281495473483474", + "valid": true, + "kind": "compute", + "expect": 9.281495473483474, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [8.507283, 17.788778] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 8.50728 and thermodynamic temperature of 17.7888.", + "a": "9.281495473483474", + "valid": true, + "kind": "compute", + "expect": 9.281495473483474, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [8.507283, 17.788778] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 6.34623 and thermodynamic temperature 21.511?", + "a": "15.164790256952909", + "valid": true, + "kind": "compute", + "expect": 15.164790256952909, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [6.346226, 21.511016] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 6.34623 and thermodynamic temperature of 21.511.", + "a": "15.164790256952909", + "valid": true, + "kind": "compute", + "expect": 15.164790256952909, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [6.346226, 21.511016] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 1.64379 and thermodynamic temperature 252.709?", + "a": "251.06522875466473", + "valid": true, + "kind": "compute", + "expect": 251.06522875466473, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [1.643795, 252.709024] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 1.64379 and thermodynamic temperature of 252.709.", + "a": "251.06522875466473", + "valid": true, + "kind": "compute", + "expect": 251.06522875466473, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [1.643795, 252.709024] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 21.7931 and thermodynamic temperature 29.5106?", + "a": "7.717482167609866", + "valid": true, + "kind": "compute", + "expect": 7.717482167609866, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [21.793126, 29.510609] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 21.7931 and thermodynamic temperature of 29.5106.", + "a": "7.717482167609866", + "valid": true, + "kind": "compute", + "expect": 7.717482167609866, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [21.793126, 29.510609] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 7.10705 and thermodynamic temperature 30.2507?", + "a": "23.143700093865256", + "valid": true, + "kind": "compute", + "expect": 23.143700093865256, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [7.107049, 30.250749] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 7.10705 and thermodynamic temperature of 30.2507.", + "a": "23.143700093865256", + "valid": true, + "kind": "compute", + "expect": 23.143700093865256, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [7.107049, 30.250749] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 0.869111 and thermodynamic temperature 39.1753?", + "a": "38.3061515435122", + "valid": true, + "kind": "compute", + "expect": 38.3061515435122, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.869111, 39.175263] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Tell me the reference temperature with temperature difference of 0.869111 and thermodynamic temperature of 39.1753.", + "a": "38.3061515435122", + "valid": true, + "kind": "compute", + "expect": 38.3061515435122, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.869111, 39.175263] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "What is the reference temperature for temperature difference 8.50728?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Tell me the reference temperature with temperature difference of 6.34623.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "What is the reference temperature of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reference temperature of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reference temperature with temperature difference of -1.64379 and thermodynamic temperature of 252.709.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative temperature difference: no example had one" + }, + { + "q": "Which reference temperature is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the temperature difference is 169.527 and the thermodynamic temperature is 280.774, what is the reference temperature?", + "a": "111.24674440201241", + "valid": true, + "kind": "compute", + "expect": 111.24674440201241, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [169.526958, 280.773702] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Could you work out the reference temperature given temperature difference = 169.527, thermodynamic temperature = 280.774?", + "a": "111.24674440201241", + "valid": true, + "kind": "compute", + "expect": 111.24674440201241, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [169.526958, 280.773702] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "I need the reference temperature for a temperature difference of 0.318734 and a thermodynamic temperature of 9.56607, please.", + "a": "9.24733694103161", + "valid": true, + "kind": "compute", + "expect": 9.24733694103161, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.318734, 9.566071] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "If the temperature difference is 0.318734 and the thermodynamic temperature is 9.56607, what is the reference temperature?", + "a": "9.24733694103161", + "valid": true, + "kind": "compute", + "expect": 9.24733694103161, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.318734, 9.566071] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Could you work out the reference temperature given temperature difference = 0.671697, thermodynamic temperature = 14.2496?", + "a": "13.57787211614313", + "valid": true, + "kind": "compute", + "expect": 13.57787211614313, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.671697, 14.249569] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "I need the reference temperature for a temperature difference of 0.671697 and a thermodynamic temperature of 14.2496, please.", + "a": "13.57787211614313", + "valid": true, + "kind": "compute", + "expect": 13.57787211614313, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [0.671697, 14.249569] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "If the temperature difference is 156.502 and the thermodynamic temperature is 185.886, what is the reference temperature?", + "a": "29.38446301183552", + "valid": true, + "kind": "compute", + "expect": 29.38446301183552, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [156.50181, 185.886273] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Could you work out the reference temperature given temperature difference = 156.502, thermodynamic temperature = 185.886?", + "a": "29.38446301183552", + "valid": true, + "kind": "compute", + "expect": 29.38446301183552, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [156.50181, 185.886273] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "I need the reference temperature for a temperature difference of 24.5721 and a thermodynamic temperature of 108.451, please.", + "a": "83.87870607231024", + "valid": true, + "kind": "compute", + "expect": 83.87870607231024, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [24.572086, 108.450792] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "If the temperature difference is 24.5721 and the thermodynamic temperature is 108.451, what is the reference temperature?", + "a": "83.87870607231024", + "valid": true, + "kind": "compute", + "expect": 83.87870607231024, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [24.572086, 108.450792] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "Could you work out the reference temperature given temperature difference = 4.07774, thermodynamic temperature = 276.408?", + "a": "272.32983938133856", + "valid": true, + "kind": "compute", + "expect": 272.32983938133856, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [4.077743, 276.407582] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "I need the reference temperature for a temperature difference of 4.07774 and a thermodynamic temperature of 276.408, please.", + "a": "272.32983938133856", + "valid": true, + "kind": "compute", + "expect": 272.32983938133856, + "dtype": "quantity", + "unit": "K", + "why": "reference temperature for [4.077743, 276.407582] (the system temperature difference (Wikidata Q69362767))" + }, + { + "q": "If the temperature difference is 169.527, what is the reference temperature?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Could you work out the reference temperature given temperature difference = 0.318734?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermodynamic temperature is not given" + }, + { + "q": "Do you know the reference temperature of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reference temperature of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reference temperature given temperature difference = -0.671697, thermodynamic temperature = 14.2496?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative temperature difference: no example had one" + }, + { + "q": "What is a typical reference temperature?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reference-temperature/program.py b/root/organs10/physics/specialists/solved-reference-temperature/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3379dcbbf748599f9e12cbdc709be80f5a4fd127 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-temperature/program.py @@ -0,0 +1,7 @@ +"""reference temperature from temperature difference, thermodynamic temperature (temperature difference (Wikidata Q69362767)) +The maths organ (systems.py): solved from the system q1 = q2 - q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(temperature_difference, thermodynamic_temperature): + return -1.0*temperature_difference + 1.0*thermodynamic_temperature diff --git a/root/organs10/physics/specialists/solved-reference-temperature/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reference-temperature/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-temperature/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reference-volume/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reference-volume/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-volume/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reference-volume/panel.json b/root/organs10/physics/specialists/solved-reference-volume/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..8b91b42c4763fb993bb41578b2b5ca03006d8645 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-volume/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reference volume for volume strain 107.961 and change in volume 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [107.960666, 59.4105] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 107.961 and change in volume of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [107.960666, 59.4105] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 169.527 and change in volume 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [169.526958, 280.773702] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 169.527 and change in volume of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [169.526958, 280.773702] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 1.91195 and change in volume 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [1.911952, 82.240072] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 1.91195 and change in volume of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [1.911952, 82.240072] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 1.64379 and change in volume 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [1.643795, 252.709024] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 1.64379 and change in volume of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [1.643795, 252.709024] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 18.3169 and change in volume 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [18.316867, 6.838598] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 18.3169 and change in volume of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [18.316867, 6.838598] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 156.502 and change in volume 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [156.50181, 185.886273] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Tell me the reference volume with volume strain of 156.502 and change in volume of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [156.50181, 185.886273] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "What is the reference volume for volume strain 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in volume is not given" + }, + { + "q": "Tell me the reference volume with volume strain of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in volume is not given" + }, + { + "q": "What is the reference volume of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reference volume of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reference volume with volume strain of -1.91195 and change in volume of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume strain: no example had one" + }, + { + "q": "Which reference volume is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the volume strain is 8.50728 and the change in volume is 17.7888, what is the reference volume?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [8.507283, 17.788778] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Could you work out the reference volume given volume strain = 8.50728, change in volume = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [8.507283, 17.788778] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "I need the reference volume for a volume strain of 8.24951 and a change in volume of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [8.24951, 0.634021] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "If the volume strain is 8.24951 and the change in volume is 0.634021, what is the reference volume?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [8.24951, 0.634021] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Could you work out the reference volume given volume strain = 0.318734, change in volume = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [0.318734, 9.566071] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "I need the reference volume for a volume strain of 0.318734 and a change in volume of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [0.318734, 9.566071] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "If the volume strain is 0.671697 and the change in volume is 14.2496, what is the reference volume?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [0.671697, 14.249569] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Could you work out the reference volume given volume strain = 0.671697, change in volume = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [0.671697, 14.249569] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "I need the reference volume for a volume strain of 21.7931 and a change in volume of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [21.793126, 29.510609] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "If the volume strain is 21.7931 and the change in volume is 29.5106, what is the reference volume?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [21.793126, 29.510609] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "Could you work out the reference volume given volume strain = 153.15, change in volume = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [153.149965, 18.595315] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "I need the reference volume for a volume strain of 153.15 and a change in volume of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "m^3", + "why": "reference volume for [153.149965, 18.595315] (the system volume strain (Wikidata Q73432507))" + }, + { + "q": "If the volume strain is 8.50728, what is the reference volume?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in volume is not given" + }, + { + "q": "Could you work out the reference volume given volume strain = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the change in volume is not given" + }, + { + "q": "Do you know the reference volume of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reference volume of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reference volume given volume strain = -0.318734, change in volume = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative volume strain: no example had one" + }, + { + "q": "What is a typical reference volume?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reference-volume/program.py b/root/organs10/physics/specialists/solved-reference-volume/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8b7424470e9ad83b2cdd1d538032a98418137973 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-volume/program.py @@ -0,0 +1,7 @@ +"""reference volume from volume strain, change in volume (volume strain (Wikidata Q73432507)) +The maths organ (systems.py): solved from the system q1 = q2 / q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(volume_strain, change_in_volume): + return 1.0*change_in_volume/volume_strain diff --git a/root/organs10/physics/specialists/solved-reference-volume/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reference-volume/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reference-volume/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reflectance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reflectance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflectance/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reflectance/panel.json b/root/organs10/physics/specialists/solved-reflectance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0c0de71d546ac9a1d50e09fac98a4c9ff488b029 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflectance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reflectance for reflected radiant flux 107.961 and incident radiant flux 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [107.960666, 59.4105] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 107.961 and incident radiant flux of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [107.960666, 59.4105] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 169.527 and incident radiant flux 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [169.526958, 280.773702] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 169.527 and incident radiant flux of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [169.526958, 280.773702] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 1.91195 and incident radiant flux 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [1.911952, 82.240072] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 1.91195 and incident radiant flux of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [1.911952, 82.240072] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 1.64379 and incident radiant flux 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [1.643795, 252.709024] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 1.64379 and incident radiant flux of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [1.643795, 252.709024] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 18.3169 and incident radiant flux 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [18.316867, 6.838598] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 18.3169 and incident radiant flux of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [18.316867, 6.838598] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 156.502 and incident radiant flux 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [156.50181, 185.886273] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 156.502 and incident radiant flux of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [156.50181, 185.886273] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflectance for reflected radiant flux 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the incident radiant flux is not given" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the incident radiant flux is not given" + }, + { + "q": "What is the reflectance of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reflectance of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reflectance with reflected radiant flux of -1.91195 and incident radiant flux of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reflected radiant flux: no example had one" + }, + { + "q": "Which reflectance is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the reflected radiant flux is 8.50728 and the incident radiant flux is 17.7888, what is the reflectance?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [8.507283, 17.788778] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = 8.50728, incident radiant flux = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [8.507283, 17.788778] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflectance for a reflected radiant flux of 8.24951 and an incident radiant flux of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [8.24951, 0.634021] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the reflected radiant flux is 8.24951 and the incident radiant flux is 0.634021, what is the reflectance?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [8.24951, 0.634021] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = 0.318734, incident radiant flux = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [0.318734, 9.566071] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflectance for a reflected radiant flux of 0.318734 and an incident radiant flux of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [0.318734, 9.566071] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the reflected radiant flux is 0.671697 and the incident radiant flux is 14.2496, what is the reflectance?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [0.671697, 14.249569] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = 0.671697, incident radiant flux = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [0.671697, 14.249569] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflectance for a reflected radiant flux of 21.7931 and an incident radiant flux of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [21.793126, 29.510609] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the reflected radiant flux is 21.7931 and the incident radiant flux is 29.5106, what is the reflectance?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [21.793126, 29.510609] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = 153.15, incident radiant flux = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [153.149965, 18.595315] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflectance for a reflected radiant flux of 153.15 and an incident radiant flux of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "reflectance for [153.149965, 18.595315] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the reflected radiant flux is 8.50728, what is the reflectance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the incident radiant flux is not given" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the incident radiant flux is not given" + }, + { + "q": "Do you know the reflectance of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reflectance of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reflectance given reflected radiant flux = -0.318734, incident radiant flux = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reflected radiant flux: no example had one" + }, + { + "q": "What is a typical reflectance?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reflectance/program.py b/root/organs10/physics/specialists/solved-reflectance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2ade6e3fe1eeadde369cf7f337a2d324e1c2742e --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflectance/program.py @@ -0,0 +1,7 @@ +"""reflectance from reflected radiant flux, incident radiant flux (reflectance (Wikidata Q663650)) +The maths organ (systems.py): solved from the system q2 = ((q0)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(reflected_radiant_flux, incident_radiant_flux): + return 1.0*reflected_radiant_flux/incident_radiant_flux diff --git a/root/organs10/physics/specialists/solved-reflectance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reflectance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflectance/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-reflected-radiant-flux/organ_formula_v2.py b/root/organs10/physics/specialists/solved-reflected-radiant-flux/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflected-radiant-flux/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-reflected-radiant-flux/panel.json b/root/organs10/physics/specialists/solved-reflected-radiant-flux/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e406f663247a0e446c13a25469fcb6df26fc5095 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflected-radiant-flux/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the reflected radiant flux for incident radiant flux 107.961 and reflectance 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [107.960666, 59.4105] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 107.961 and reflectance of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [107.960666, 59.4105] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 169.527 and reflectance 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [169.526958, 280.773702] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 169.527 and reflectance of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [169.526958, 280.773702] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 1.91195 and reflectance 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [1.911952, 82.240072] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 1.91195 and reflectance of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [1.911952, 82.240072] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 1.64379 and reflectance 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [1.643795, 252.709024] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 1.64379 and reflectance of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [1.643795, 252.709024] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 18.3169 and reflectance 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [18.316867, 6.838598] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 18.3169 and reflectance of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [18.316867, 6.838598] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 156.502 and reflectance 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [156.50181, 185.886273] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 156.502 and reflectance of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [156.50181, 185.886273] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "What is the reflected radiant flux for incident radiant flux 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the reflectance is not given" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the reflectance is not given" + }, + { + "q": "What is the reflected radiant flux of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the reflected radiant flux of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the reflected radiant flux with incident radiant flux of -1.91195 and reflectance of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative incident radiant flux: no example had one" + }, + { + "q": "Which reflected radiant flux is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the incident radiant flux is 8.50728 and the reflectance is 17.7888, what is the reflected radiant flux?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [8.507283, 17.788778] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = 8.50728, reflectance = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [8.507283, 17.788778] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflected radiant flux for an incident radiant flux of 8.24951 and a reflectance of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [8.24951, 0.634021] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the incident radiant flux is 8.24951 and the reflectance is 0.634021, what is the reflected radiant flux?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [8.24951, 0.634021] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = 0.318734, reflectance = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [0.318734, 9.566071] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflected radiant flux for an incident radiant flux of 0.318734 and a reflectance of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [0.318734, 9.566071] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the incident radiant flux is 0.671697 and the reflectance is 14.2496, what is the reflected radiant flux?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [0.671697, 14.249569] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = 0.671697, reflectance = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [0.671697, 14.249569] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflected radiant flux for an incident radiant flux of 21.7931 and a reflectance of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [21.793126, 29.510609] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the incident radiant flux is 21.7931 and the reflectance is 29.5106, what is the reflected radiant flux?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [21.793126, 29.510609] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = 153.15, reflectance = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [153.149965, 18.595315] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "I need the reflected radiant flux for an incident radiant flux of 153.15 and a reflectance of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "reflected radiant flux for [153.149965, 18.595315] (the system reflectance (Wikidata Q663650))" + }, + { + "q": "If the incident radiant flux is 8.50728, what is the reflected radiant flux?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the reflectance is not given" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the reflectance is not given" + }, + { + "q": "Do you know the reflected radiant flux of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the reflected radiant flux of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the reflected radiant flux given incident radiant flux = -0.318734, reflectance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative incident radiant flux: no example had one" + }, + { + "q": "What is a typical reflected radiant flux?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-reflected-radiant-flux/program.py b/root/organs10/physics/specialists/solved-reflected-radiant-flux/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3838b4d6ee99a05d140af3905981aedab34a509b --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflected-radiant-flux/program.py @@ -0,0 +1,7 @@ +"""reflected radiant flux from incident radiant flux, reflectance (reflectance (Wikidata Q663650)) +The maths organ (systems.py): solved from the system q2 = ((q0)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(incident_radiant_flux, reflectance): + return 1.0*incident_radiant_flux*reflectance diff --git a/root/organs10/physics/specialists/solved-reflected-radiant-flux/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-reflected-radiant-flux/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-reflected-radiant-flux/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-refractive-index-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-refractive-index-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-refractive-index-2/panel.json b/root/organs10/physics/specialists/solved-refractive-index-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7b8f20e02666f8222a56c3b8d7cf7e0f735565ca --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the refractive index for speed of light in a medium 107.961?", + "a": "2037779.2058473695", + "valid": true, + "kind": "compute", + "expect": 2037779.2058473695, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [107.960666] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 107.961.", + "a": "2037779.2058473695", + "valid": true, + "kind": "compute", + "expect": 2037779.2058473695, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [107.960666] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index for speed of light in a medium 22.652?", + "a": "9712156.921832915", + "valid": true, + "kind": "compute", + "expect": 9712156.921832915, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [22.652023] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 22.652.", + "a": "9712156.921832915", + "valid": true, + "kind": "compute", + "expect": 9712156.921832915, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [22.652023] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index for speed of light in a medium 173.394?", + "a": "1268789.339812782", + "valid": true, + "kind": "compute", + "expect": 1268789.339812782, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [173.393638] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 173.394.", + "a": "1268789.339812782", + "valid": true, + "kind": "compute", + "expect": 1268789.339812782, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [173.393638] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index for speed of light in a medium 126.709?", + "a": "1736258.3779354568", + "valid": true, + "kind": "compute", + "expect": 1736258.3779354568, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [126.709252] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 126.709.", + "a": "1736258.3779354568", + "valid": true, + "kind": "compute", + "expect": 1736258.3779354568, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [126.709252] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index for speed of light in a medium 0.671697?", + "a": "327528535.2795985", + "valid": true, + "kind": "compute", + "expect": 327528535.2795985, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.671697] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 0.671697.", + "a": "327528535.2795985", + "valid": true, + "kind": "compute", + "expect": 327528535.2795985, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.671697] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index for speed of light in a medium 1.16997?", + "a": "188039330.02946487", + "valid": true, + "kind": "compute", + "expect": 188039330.02946487, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [1.169968] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of 1.16997.", + "a": "188039330.02946487", + "valid": true, + "kind": "compute", + "expect": 188039330.02946487, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [1.169968] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "What is the refractive index?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed of light in a medium is not given" + }, + { + "q": "Could you work out the refractive index, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed of light in a medium is not given" + }, + { + "q": "What is the refractive index of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the refractive index of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the refractive index with speed of light in a medium of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed of light in a medium: no example had one" + }, + { + "q": "Which refractive index is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the speed of light in a medium is 2.57003, what is the refractive index?", + "a": "85602116.48167203", + "valid": true, + "kind": "compute", + "expect": 85602116.48167203, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [2.57003] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Could you work out the refractive index given speed of light in a medium = 2.57003?", + "a": "85602116.48167203", + "valid": true, + "kind": "compute", + "expect": 85602116.48167203, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [2.57003] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "I need the refractive index for a speed of light in a medium of 48.921, please.", + "a": "4497047.0984435575", + "valid": true, + "kind": "compute", + "expect": 4497047.0984435575, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [48.920991] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "If the speed of light in a medium is 48.921, what is the refractive index?", + "a": "4497047.0984435575", + "valid": true, + "kind": "compute", + "expect": 4497047.0984435575, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [48.920991] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Could you work out the refractive index given speed of light in a medium = 0.348438?", + "a": "631389827.1492717", + "valid": true, + "kind": "compute", + "expect": 631389827.1492717, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.348438] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "I need the refractive index for a speed of light in a medium of 0.348438, please.", + "a": "631389827.1492717", + "valid": true, + "kind": "compute", + "expect": 631389827.1492717, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.348438] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "If the speed of light in a medium is 252.709, what is the refractive index?", + "a": "870566.457424052", + "valid": true, + "kind": "compute", + "expect": 870566.457424052, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [252.709024] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Could you work out the refractive index given speed of light in a medium = 252.709?", + "a": "870566.457424052", + "valid": true, + "kind": "compute", + "expect": 870566.457424052, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [252.709024] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "I need the refractive index for a speed of light in a medium of 20.3966, please.", + "a": "10786133.641287291", + "valid": true, + "kind": "compute", + "expect": 10786133.641287291, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [20.396558] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "If the speed of light in a medium is 20.3966, what is the refractive index?", + "a": "10786133.641287291", + "valid": true, + "kind": "compute", + "expect": 10786133.641287291, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [20.396558] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "Could you work out the refractive index given speed of light in a medium = 134.993?", + "a": "1629714.645435634", + "valid": true, + "kind": "compute", + "expect": 1629714.645435634, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [134.992958] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "I need the refractive index for a speed of light in a medium of 134.993, please.", + "a": "1629714.645435634", + "valid": true, + "kind": "compute", + "expect": 1629714.645435634, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [134.992958] (the system refractive index (Wikidata Q174102))" + }, + { + "q": "I need the refractive index, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed of light in a medium is not given" + }, + { + "q": "Can you tell me the refractive index?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed of light in a medium is not given" + }, + { + "q": "Do you know the refractive index of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the refractive index of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the refractive index given speed of light in a medium = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed of light in a medium: no example had one" + }, + { + "q": "What is a typical refractive index?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-refractive-index-2/program.py b/root/organs10/physics/specialists/solved-refractive-index-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d6cfee7a0a89d82be95c1b4d30dd133136f332c3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index-2/program.py @@ -0,0 +1,7 @@ +"""refractive index from speed of light in a medium (refractive index (Wikidata Q174102)) +The maths organ (systems.py): solved from the system q1 = ((q0)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(speed_of_light_in_a_medium): + return 220000000.0/speed_of_light_in_a_medium diff --git a/root/organs10/physics/specialists/solved-refractive-index-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-refractive-index-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-refractive-index/organ_formula_v2.py b/root/organs10/physics/specialists/solved-refractive-index/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-refractive-index/panel.json b/root/organs10/physics/specialists/solved-refractive-index/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..52d5c9afc103577d280df0c544408e16b0442c8d --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the refractive index for refractivity 107.961?", + "a": "108.96066588996202", + "valid": true, + "kind": "compute", + "expect": 108.96066588996202, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [107.960666] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 107.961.", + "a": "108.96066588996202", + "valid": true, + "kind": "compute", + "expect": 108.96066588996202, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [107.960666] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index for refractivity 22.652?", + "a": "23.652022796855793", + "valid": true, + "kind": "compute", + "expect": 23.652022796855793, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [22.652023] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 22.652.", + "a": "23.652022796855793", + "valid": true, + "kind": "compute", + "expect": 23.652022796855793, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [22.652023] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index for refractivity 173.394?", + "a": "174.3936384053025", + "valid": true, + "kind": "compute", + "expect": 174.3936384053025, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [173.393638] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 173.394.", + "a": "174.3936384053025", + "valid": true, + "kind": "compute", + "expect": 174.3936384053025, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [173.393638] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index for refractivity 126.709?", + "a": "127.70925180018237", + "valid": true, + "kind": "compute", + "expect": 127.70925180018237, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [126.709252] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 126.709.", + "a": "127.70925180018237", + "valid": true, + "kind": "compute", + "expect": 127.70925180018237, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [126.709252] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index for refractivity 0.671697?", + "a": "1.6716971997941936", + "valid": true, + "kind": "compute", + "expect": 1.6716971997941936, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.671697] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 0.671697.", + "a": "1.6716971997941936", + "valid": true, + "kind": "compute", + "expect": 1.6716971997941936, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.671697] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index for refractivity 1.16997?", + "a": "2.169968005977936", + "valid": true, + "kind": "compute", + "expect": 2.169968005977936, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [1.169968] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractive index with refractivity of 1.16997.", + "a": "2.169968005977936", + "valid": true, + "kind": "compute", + "expect": 2.169968005977936, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [1.169968] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractive index?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractivity is not given" + }, + { + "q": "Could you work out the refractive index, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractivity is not given" + }, + { + "q": "What is the refractive index of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the refractive index of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the refractive index with refractivity of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative refractivity: no example had one" + }, + { + "q": "Which refractive index is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the refractivity is 2.57003, what is the refractive index?", + "a": "3.5700299133036437", + "valid": true, + "kind": "compute", + "expect": 3.5700299133036437, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [2.57003] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractive index given refractivity = 2.57003?", + "a": "3.5700299133036437", + "valid": true, + "kind": "compute", + "expect": 3.5700299133036437, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [2.57003] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractive index for a refractivity of 48.921, please.", + "a": "49.920990860011834", + "valid": true, + "kind": "compute", + "expect": 49.920990860011834, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [48.920991] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractivity is 48.921, what is the refractive index?", + "a": "49.920990860011834", + "valid": true, + "kind": "compute", + "expect": 49.920990860011834, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [48.920991] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractive index given refractivity = 0.348438?", + "a": "1.3484376696300304", + "valid": true, + "kind": "compute", + "expect": 1.3484376696300304, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.348438] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractive index for a refractivity of 0.348438, please.", + "a": "1.3484376696300304", + "valid": true, + "kind": "compute", + "expect": 1.3484376696300304, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [0.348438] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractivity is 252.709, what is the refractive index?", + "a": "253.70902424952752", + "valid": true, + "kind": "compute", + "expect": 253.70902424952752, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [252.709024] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractive index given refractivity = 252.709?", + "a": "253.70902424952752", + "valid": true, + "kind": "compute", + "expect": 253.70902424952752, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [252.709024] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractive index for a refractivity of 20.3966, please.", + "a": "21.39655796196344", + "valid": true, + "kind": "compute", + "expect": 21.39655796196344, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [20.396558] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractivity is 20.3966, what is the refractive index?", + "a": "21.39655796196344", + "valid": true, + "kind": "compute", + "expect": 21.39655796196344, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [20.396558] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractive index given refractivity = 134.993?", + "a": "135.992957580738", + "valid": true, + "kind": "compute", + "expect": 135.992957580738, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [134.992958] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractive index for a refractivity of 134.993, please.", + "a": "135.992957580738", + "valid": true, + "kind": "compute", + "expect": 135.992957580738, + "dtype": "quantity", + "unit": "1", + "why": "refractive index for [134.992958] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractive index, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractivity is not given" + }, + { + "q": "Can you tell me the refractive index?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractivity is not given" + }, + { + "q": "Do you know the refractive index of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the refractive index of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the refractive index given refractivity = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative refractivity: no example had one" + }, + { + "q": "What is a typical refractive index?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-refractive-index/program.py b/root/organs10/physics/specialists/solved-refractive-index/program.py new file mode 100644 index 0000000000000000000000000000000000000000..f33c1e42fc61e7c824c7e7a67e35f8a1249b841d --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index/program.py @@ -0,0 +1,7 @@ +"""refractive index from refractivity (refractivity (Wikidata Q108074352)) +The maths organ (systems.py): solved from the system q0 = q1 - 1; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(refractivity): + return 1.0*refractivity + 1.0 diff --git a/root/organs10/physics/specialists/solved-refractive-index/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-refractive-index/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractive-index/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-refractivity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-refractivity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractivity/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-refractivity/panel.json b/root/organs10/physics/specialists/solved-refractivity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f74fc5ca54130fa24f495e1d02777e736949a239 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractivity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the refractivity for refractive index 107.961?", + "a": "106.96066588996202", + "valid": true, + "kind": "compute", + "expect": 106.96066588996202, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [107.960666] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 107.961.", + "a": "106.96066588996202", + "valid": true, + "kind": "compute", + "expect": 106.96066588996202, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [107.960666] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity for refractive index 22.652?", + "a": "21.652022796855793", + "valid": true, + "kind": "compute", + "expect": 21.652022796855793, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [22.652023] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 22.652.", + "a": "21.652022796855793", + "valid": true, + "kind": "compute", + "expect": 21.652022796855793, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [22.652023] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity for refractive index 173.394?", + "a": "172.3936384053025", + "valid": true, + "kind": "compute", + "expect": 172.3936384053025, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [173.393638] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 173.394.", + "a": "172.3936384053025", + "valid": true, + "kind": "compute", + "expect": 172.3936384053025, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [173.393638] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity for refractive index 1.70503?", + "a": "0.7050323785741319", + "valid": true, + "kind": "compute", + "expect": 0.7050323785741319, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [1.705032] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 1.70503.", + "a": "0.7050323785741319", + "valid": true, + "kind": "compute", + "expect": 0.7050323785741319, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [1.705032] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity for refractive index 14.2496?", + "a": "13.249569315937324", + "valid": true, + "kind": "compute", + "expect": 13.249569315937324, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [14.249569] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 14.2496.", + "a": "13.249569315937324", + "valid": true, + "kind": "compute", + "expect": 13.249569315937324, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [14.249569] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity for refractive index 1.14865?", + "a": "0.14865229534509616", + "valid": true, + "kind": "compute", + "expect": 0.14865229534509616, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [1.148652] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Tell me the refractivity with refractive index of 1.14865.", + "a": "0.14865229534509616", + "valid": true, + "kind": "compute", + "expect": 0.14865229534509616, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [1.148652] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "What is the refractivity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractive index is not given" + }, + { + "q": "Could you work out the refractivity, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractive index is not given" + }, + { + "q": "What is the refractivity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the refractivity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the refractivity with refractive index of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative refractive index: no example had one" + }, + { + "q": "Which refractivity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the refractive index is 2.57003, what is the refractivity?", + "a": "1.5700299133036437", + "valid": true, + "kind": "compute", + "expect": 1.5700299133036437, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [2.57003] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractivity given refractive index = 2.57003?", + "a": "1.5700299133036437", + "valid": true, + "kind": "compute", + "expect": 1.5700299133036437, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [2.57003] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractivity for a refractive index of 48.921, please.", + "a": "47.920990860011834", + "valid": true, + "kind": "compute", + "expect": 47.920990860011834, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [48.920991] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractive index is 48.921, what is the refractivity?", + "a": "47.920990860011834", + "valid": true, + "kind": "compute", + "expect": 47.920990860011834, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [48.920991] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractivity given refractive index = 45.6157?", + "a": "44.61567011302099", + "valid": true, + "kind": "compute", + "expect": 44.61567011302099, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [45.61567] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractivity for a refractive index of 45.6157, please.", + "a": "44.61567011302099", + "valid": true, + "kind": "compute", + "expect": 44.61567011302099, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [45.61567] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractive index is 81.1967, what is the refractivity?", + "a": "80.19670539498256", + "valid": true, + "kind": "compute", + "expect": 80.19670539498256, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [81.196705] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractivity given refractive index = 81.1967?", + "a": "80.19670539498256", + "valid": true, + "kind": "compute", + "expect": 80.19670539498256, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [81.196705] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractivity for a refractive index of 18.3169, please.", + "a": "17.31686702277652", + "valid": true, + "kind": "compute", + "expect": 17.31686702277652, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [18.316867] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "If the refractive index is 18.3169, what is the refractivity?", + "a": "17.31686702277652", + "valid": true, + "kind": "compute", + "expect": 17.31686702277652, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [18.316867] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "Could you work out the refractivity given refractive index = 186.27?", + "a": "185.27005716121914", + "valid": true, + "kind": "compute", + "expect": 185.27005716121914, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [186.270057] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractivity for a refractive index of 186.27, please.", + "a": "185.27005716121914", + "valid": true, + "kind": "compute", + "expect": 185.27005716121914, + "dtype": "quantity", + "unit": "1", + "why": "refractivity for [186.270057] (the system refractivity (Wikidata Q108074352))" + }, + { + "q": "I need the refractivity, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractive index is not given" + }, + { + "q": "Can you tell me the refractivity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the refractive index is not given" + }, + { + "q": "Do you know the refractivity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the refractivity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the refractivity given refractive index = -45.6157?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative refractive index: no example had one" + }, + { + "q": "What is a typical refractivity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-refractivity/program.py b/root/organs10/physics/specialists/solved-refractivity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d00eeeb3619754ccf620af357c28da82bee3d14a --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractivity/program.py @@ -0,0 +1,7 @@ +"""refractivity from refractive index (refractivity (Wikidata Q108074352)) +The maths organ (systems.py): solved from the system q0 = q1 - 1; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(refractive_index): + return 1.0*refractive_index - 1.0 diff --git a/root/organs10/physics/specialists/solved-refractivity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-refractivity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-refractivity/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-atomic-mass/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-atomic-mass/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-atomic-mass/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-atomic-mass/panel.json b/root/organs10/physics/specialists/solved-relative-atomic-mass/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f04e73ae13276f47ad96869e6af418d3090e4472 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-atomic-mass/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative atomic mass for average atomic mass 107.961?", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [107.960666] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 107.961.", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [107.960666] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass for average atomic mass 22.652?", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [22.652023] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 22.652.", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [22.652023] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass for average atomic mass 173.394?", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [173.393638] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 173.394.", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [173.393638] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass for average atomic mass 126.709?", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [126.709252] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 126.709.", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [126.709252] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass for average atomic mass 0.671697?", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [0.671697] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 0.671697.", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [0.671697] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass for average atomic mass 1.16997?", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [1.169968] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of 1.16997.", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [1.169968] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "What is the relative atomic mass?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the average atomic mass is not given" + }, + { + "q": "Could you work out the relative atomic mass, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the average atomic mass is not given" + }, + { + "q": "What is the relative atomic mass of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative atomic mass of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative atomic mass with average atomic mass of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative average atomic mass: no example had one" + }, + { + "q": "Which relative atomic mass is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the average atomic mass is 2.57003, what is the relative atomic mass?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [2.57003] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Could you work out the relative atomic mass given average atomic mass = 2.57003?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [2.57003] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "I need the relative atomic mass for an average atomic mass of 48.921, please.", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [48.920991] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "If the average atomic mass is 48.921, what is the relative atomic mass?", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [48.920991] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Could you work out the relative atomic mass given average atomic mass = 0.348438?", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [0.348438] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "I need the relative atomic mass for an average atomic mass of 0.348438, please.", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [0.348438] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "If the average atomic mass is 252.709, what is the relative atomic mass?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [252.709024] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Could you work out the relative atomic mass given average atomic mass = 252.709?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [252.709024] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "I need the relative atomic mass for an average atomic mass of 20.3966, please.", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [20.396558] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "If the average atomic mass is 20.3966, what is the relative atomic mass?", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [20.396558] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "Could you work out the relative atomic mass given average atomic mass = 134.993?", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [134.992958] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "I need the relative atomic mass for an average atomic mass of 134.993, please.", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative atomic mass for [134.992958] (the system relative atomic mass (Wikidata Q41377))" + }, + { + "q": "I need the relative atomic mass, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the average atomic mass is not given" + }, + { + "q": "Can you tell me the relative atomic mass?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the average atomic mass is not given" + }, + { + "q": "Do you know the relative atomic mass of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative atomic mass of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative atomic mass given average atomic mass = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative average atomic mass: no example had one" + }, + { + "q": "What is a typical relative atomic mass?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-atomic-mass/program.py b/root/organs10/physics/specialists/solved-relative-atomic-mass/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a44523ff9f813997849de84e380c9779c907c3f0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-atomic-mass/program.py @@ -0,0 +1,7 @@ +"""relative atomic mass from average atomic mass (relative atomic mass (Wikidata Q41377)) +The maths organ (systems.py): solved from the system q1 = ((q0)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(average_atomic_mass): + return 6.02214076208112e+26*average_atomic_mass diff --git a/root/organs10/physics/specialists/solved-relative-atomic-mass/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-atomic-mass/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-atomic-mass/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-density/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-density/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-density/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-density/panel.json b/root/organs10/physics/specialists/solved-relative-density/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f8a80ba037b1e11d0aa6d889434b1d08bfe72a42 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-density/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative density for reference density 107.961 and mass density 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [107.960666, 59.4105] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 107.961 and mass density of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [107.960666, 59.4105] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 169.527 and mass density 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [169.526958, 280.773702] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 169.527 and mass density of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [169.526958, 280.773702] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 1.91195 and mass density 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [1.911952, 82.240072] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 1.91195 and mass density of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [1.911952, 82.240072] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 1.64379 and mass density 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [1.643795, 252.709024] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 1.64379 and mass density of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [1.643795, 252.709024] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 18.3169 and mass density 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [18.316867, 6.838598] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 18.3169 and mass density of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [18.316867, 6.838598] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 156.502 and mass density 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [156.50181, 185.886273] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Tell me the relative density with reference density of 156.502 and mass density of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [156.50181, 185.886273] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "What is the relative density for reference density 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Tell me the relative density with reference density of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "What is the relative density of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative density of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative density with reference density of -1.91195 and mass density of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reference density: no example had one" + }, + { + "q": "Which relative density is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the reference density is 8.50728 and the mass density is 17.7888, what is the relative density?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [8.507283, 17.788778] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the relative density given reference density = 8.50728, mass density = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [8.507283, 17.788778] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the relative density for a reference density of 8.24951 and a mass density of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [8.24951, 0.634021] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the reference density is 8.24951 and the mass density is 0.634021, what is the relative density?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [8.24951, 0.634021] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the relative density given reference density = 0.318734, mass density = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [0.318734, 9.566071] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the relative density for a reference density of 0.318734 and a mass density of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [0.318734, 9.566071] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the reference density is 0.671697 and the mass density is 14.2496, what is the relative density?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [0.671697, 14.249569] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the relative density given reference density = 0.671697, mass density = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [0.671697, 14.249569] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the relative density for a reference density of 21.7931 and a mass density of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [21.793126, 29.510609] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the reference density is 21.7931 and the mass density is 29.5106, what is the relative density?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [21.793126, 29.510609] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "Could you work out the relative density given reference density = 153.15, mass density = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [153.149965, 18.595315] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "I need the relative density for a reference density of 153.15 and a mass density of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative density for [153.149965, 18.595315] (the system relative density (Wikidata Q11027905))" + }, + { + "q": "If the reference density is 8.50728, what is the relative density?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Could you work out the relative density given reference density = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Do you know the relative density of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative density of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative density given reference density = -0.318734, mass density = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reference density: no example had one" + }, + { + "q": "What is a typical relative density?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-density/program.py b/root/organs10/physics/specialists/solved-relative-density/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5938f97c484733c1893ea8bb621ca648b63680bc --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-density/program.py @@ -0,0 +1,7 @@ +"""relative density from reference density, mass density (relative density (Wikidata Q11027905)) +The maths organ (systems.py): solved from the system q1 = q2 / q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(reference_density, mass_density): + return 1.0*mass_density/reference_density diff --git a/root/organs10/physics/specialists/solved-relative-density/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-density/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-density/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-mass-concentration-o/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-mass-concentration-o/panel.json b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..13bba100e07135462e571d1a919bccd00c5866a1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 107.961 and mass concentration of water vapour 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [107.960666, 59.4105] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 107.961 and mass concentration of water vapour of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [107.960666, 59.4105] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 169.527 and mass concentration of water vapour 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [169.526958, 280.773702] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 169.527 and mass concentration of water vapour of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [169.526958, 280.773702] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 1.91195 and mass concentration of water vapour 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [1.911952, 82.240072] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 1.91195 and mass concentration of water vapour of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [1.911952, 82.240072] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 1.64379 and mass concentration of water vapour 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [1.643795, 252.709024] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 1.64379 and mass concentration of water vapour of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [1.643795, 252.709024] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 18.3169 and mass concentration of water vapour 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [18.316867, 6.838598] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 18.3169 and mass concentration of water vapour of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [18.316867, 6.838598] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 156.502 and mass concentration of water vapour 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [156.50181, 185.886273] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 156.502 and mass concentration of water vapour of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [156.50181, 185.886273] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "What is the relative mass concentration of vapour for mass concentration of water vapour at saturation 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass concentration of water vapour is not given" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass concentration of water vapour is not given" + }, + { + "q": "What is the relative mass concentration of vapour of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative mass concentration of vapour of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative mass concentration of vapour with mass concentration of water vapour at saturation of -1.91195 and mass concentration of water vapour of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass concentration of water vapour at saturation: no example had one" + }, + { + "q": "Which relative mass concentration of vapour is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mass concentration of water vapour at saturation is 8.50728 and the mass concentration of water vapour is 17.7888, what is the relative mass concentration of vapour?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [8.507283, 17.788778] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = 8.50728, mass concentration of water vapour = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [8.507283, 17.788778] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "I need the relative mass concentration of vapour for a mass concentration of water vapour at saturation of 8.24951 and a mass concentration of water vapour of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [8.24951, 0.634021] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "If the mass concentration of water vapour at saturation is 8.24951 and the mass concentration of water vapour is 0.634021, what is the relative mass concentration of vapour?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [8.24951, 0.634021] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = 0.318734, mass concentration of water vapour = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [0.318734, 9.566071] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "I need the relative mass concentration of vapour for a mass concentration of water vapour at saturation of 0.318734 and a mass concentration of water vapour of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [0.318734, 9.566071] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "If the mass concentration of water vapour at saturation is 0.671697 and the mass concentration of water vapour is 14.2496, what is the relative mass concentration of vapour?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [0.671697, 14.249569] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = 0.671697, mass concentration of water vapour = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [0.671697, 14.249569] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "I need the relative mass concentration of vapour for a mass concentration of water vapour at saturation of 21.7931 and a mass concentration of water vapour of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [21.793126, 29.510609] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "If the mass concentration of water vapour at saturation is 21.7931 and the mass concentration of water vapour is 29.5106, what is the relative mass concentration of vapour?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [21.793126, 29.510609] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = 153.15, mass concentration of water vapour = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [153.149965, 18.595315] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "I need the relative mass concentration of vapour for a mass concentration of water vapour at saturation of 153.15 and a mass concentration of water vapour of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative mass concentration of vapour for [153.149965, 18.595315] (the system relative mass concentration of vapour (Wikidata Q76379357))" + }, + { + "q": "If the mass concentration of water vapour at saturation is 8.50728, what is the relative mass concentration of vapour?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass concentration of water vapour is not given" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass concentration of water vapour is not given" + }, + { + "q": "Do you know the relative mass concentration of vapour of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative mass concentration of vapour of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative mass concentration of vapour given mass concentration of water vapour at saturation = -0.318734, mass concentration of water vapour = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass concentration of water vapour at saturation: no example had one" + }, + { + "q": "What is a typical relative mass concentration of vapour?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-mass-concentration-o/program.py b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/program.py new file mode 100644 index 0000000000000000000000000000000000000000..82939de5353aa8158ef841016b8d953b11b4d833 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/program.py @@ -0,0 +1,7 @@ +"""relative mass concentration of vapour from mass concentration of water vapour at saturation, mass concentration of water vapour (relative mass concentration of vapour (Wikidata Q76379357)) +The maths organ (systems.py): solved from the system q1 = q2 / q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass_concentration_of_water_vapour_at_saturation, mass_concentration_of_water_vapour): + return 1.0*mass_concentration_of_water_vapour/mass_concentration_of_water_vapour_at_saturation diff --git a/root/organs10/physics/specialists/solved-relative-mass-concentration-o/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-concentration-o/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-mass-defect-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect-2/panel.json b/root/organs10/physics/specialists/solved-relative-mass-defect-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..35f57d6afc71c6295bf492a7d356f0d916f4d105 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative mass defect for mass defect 107.961?", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [107.960666] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 107.961.", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [107.960666] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect for mass defect 22.652?", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [22.652023] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 22.652.", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [22.652023] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect for mass defect 173.394?", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [173.393638] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 173.394.", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [173.393638] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect for mass defect 126.709?", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [126.709252] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 126.709.", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [126.709252] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect for mass defect 0.671697?", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.671697] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 0.671697.", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.671697] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect for mass defect 1.16997?", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.169968] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Tell me the relative mass defect with mass defect of 1.16997.", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.169968] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "What is the relative mass defect?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass defect is not given" + }, + { + "q": "Could you work out the relative mass defect, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass defect is not given" + }, + { + "q": "What is the relative mass defect of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative mass defect of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative mass defect with mass defect of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass defect: no example had one" + }, + { + "q": "Which relative mass defect is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mass defect is 2.57003, what is the relative mass defect?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [2.57003] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Could you work out the relative mass defect given mass defect = 2.57003?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [2.57003] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "I need the relative mass defect for a mass defect of 48.921, please.", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [48.920991] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "If the mass defect is 48.921, what is the relative mass defect?", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [48.920991] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Could you work out the relative mass defect given mass defect = 0.348438?", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.348438] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "I need the relative mass defect for a mass defect of 0.348438, please.", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.348438] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "If the mass defect is 252.709, what is the relative mass defect?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [252.709024] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Could you work out the relative mass defect given mass defect = 252.709?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [252.709024] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "I need the relative mass defect for a mass defect of 20.3966, please.", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [20.396558] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "If the mass defect is 20.3966, what is the relative mass defect?", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [20.396558] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "Could you work out the relative mass defect given mass defect = 134.993?", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [134.992958] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "I need the relative mass defect for a mass defect of 134.993, please.", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [134.992958] (the system relative mass defect (Wikidata Q98038718))" + }, + { + "q": "I need the relative mass defect, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass defect is not given" + }, + { + "q": "Can you tell me the relative mass defect?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass defect is not given" + }, + { + "q": "Do you know the relative mass defect of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative mass defect of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative mass defect given mass defect = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass defect: no example had one" + }, + { + "q": "What is a typical relative mass defect?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect-2/program.py b/root/organs10/physics/specialists/solved-relative-mass-defect-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..43bacc555f9fcdc3c778f441939c3e1ecaf72776 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect-2/program.py @@ -0,0 +1,7 @@ +"""relative mass defect from mass defect (relative mass defect (Wikidata Q98038718)) +The maths organ (systems.py): solved from the system q0 = ((q2)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass_defect): + return 6.02214076208112e+26*mass_defect diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-mass-defect-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-mass-defect/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect/panel.json b/root/organs10/physics/specialists/solved-relative-mass-defect/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3998cb4c64dab66abb535239b47d7f22b6f605db --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative mass defect for binding fraction 107.961 and mass number 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [107.960666, 59.4105] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 107.961 and mass number of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [107.960666, 59.4105] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 169.527 and mass number 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [169.526958, 280.773702] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 169.527 and mass number of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [169.526958, 280.773702] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 1.91195 and mass number 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.911952, 82.240072] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 1.91195 and mass number of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.911952, 82.240072] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 1.64379 and mass number 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.643795, 252.709024] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 1.64379 and mass number of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [1.643795, 252.709024] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 18.3169 and mass number 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [18.316867, 6.838598] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 18.3169 and mass number of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [18.316867, 6.838598] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 156.502 and mass number 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [156.50181, 185.886273] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 156.502 and mass number of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [156.50181, 185.886273] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "What is the relative mass defect for binding fraction 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass number is not given" + }, + { + "q": "Tell me the relative mass defect with binding fraction of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass number is not given" + }, + { + "q": "What is the relative mass defect of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative mass defect of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative mass defect with binding fraction of -1.91195 and mass number of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative binding fraction: no example had one" + }, + { + "q": "Which relative mass defect is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the binding fraction is 8.50728 and the mass number is 17.7888, what is the relative mass defect?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [8.507283, 17.788778] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = 8.50728, mass number = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [8.507283, 17.788778] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "I need the relative mass defect for a binding fraction of 8.24951 and a mass number of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [8.24951, 0.634021] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "If the binding fraction is 8.24951 and the mass number is 0.634021, what is the relative mass defect?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [8.24951, 0.634021] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = 0.318734, mass number = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.318734, 9.566071] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "I need the relative mass defect for a binding fraction of 0.318734 and a mass number of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.318734, 9.566071] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "If the binding fraction is 0.671697 and the mass number is 14.2496, what is the relative mass defect?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.671697, 14.249569] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = 0.671697, mass number = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [0.671697, 14.249569] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "I need the relative mass defect for a binding fraction of 21.7931 and a mass number of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [21.793126, 29.510609] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "If the binding fraction is 21.7931 and the mass number is 29.5106, what is the relative mass defect?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [21.793126, 29.510609] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = 153.15, mass number = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [153.149965, 18.595315] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "I need the relative mass defect for a binding fraction of 153.15 and a mass number of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "relative mass defect for [153.149965, 18.595315] (the system binding fraction (Wikidata Q98058362))" + }, + { + "q": "If the binding fraction is 8.50728, what is the relative mass defect?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass number is not given" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass number is not given" + }, + { + "q": "Do you know the relative mass defect of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative mass defect of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative mass defect given binding fraction = -0.318734, mass number = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative binding fraction: no example had one" + }, + { + "q": "What is a typical relative mass defect?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect/program.py b/root/organs10/physics/specialists/solved-relative-mass-defect/program.py new file mode 100644 index 0000000000000000000000000000000000000000..e5ebcff536506c25eb7b3d389ff1f5e5ccede67e --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect/program.py @@ -0,0 +1,7 @@ +"""relative mass defect from binding fraction, mass number (binding fraction (Wikidata Q98058362)) +The maths organ (systems.py): solved from the system q1 = ((q0)/(q2)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(binding_fraction, mass_number): + return 1.0*binding_fraction*mass_number diff --git a/root/organs10/physics/specialists/solved-relative-mass-defect/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-mass-defect/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-defect/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-mass-excess/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-mass-excess/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-excess/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-mass-excess/panel.json b/root/organs10/physics/specialists/solved-relative-mass-excess/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..84531bbb6f26b4d69c8f5af3e58143f8b2d906d8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-excess/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative mass excess for mass excess 107.961?", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [107.960666] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 107.961.", + "a": "6.501543267573611e+28", + "valid": true, + "kind": "compute", + "expect": 6.501543267573611e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [107.960666] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess for mass excess 22.652?", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [22.652023] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 22.652.", + "a": "1.3641366982853606e+28", + "valid": true, + "kind": "compute", + "expect": 1.3641366982853606e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [22.652023] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess for mass excess 173.394?", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [173.393638] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 173.394.", + "a": "1.0442008977261267e+29", + "valid": true, + "kind": "compute", + "expect": 1.0442008977261267e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [173.393638] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess for mass excess 126.709?", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [126.709252] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 126.709.", + "a": "7.630609501986788e+28", + "valid": true, + "kind": "compute", + "expect": 7.630609501986788e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [126.709252] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess for mass excess 0.671697?", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [0.671697] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 0.671697.", + "a": "4.0450550866563586e+26", + "valid": true, + "kind": "compute", + "expect": 4.0450550866563586e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [0.671697] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess for mass excess 1.16997?", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [1.169968] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Tell me the relative mass excess with mass excess of 1.16997.", + "a": "7.045712019130494e+26", + "valid": true, + "kind": "compute", + "expect": 7.045712019130494e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [1.169968] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "What is the relative mass excess?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass excess is not given" + }, + { + "q": "Could you work out the relative mass excess, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass excess is not given" + }, + { + "q": "What is the relative mass excess of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative mass excess of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative mass excess with mass excess of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass excess: no example had one" + }, + { + "q": "Which relative mass excess is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mass excess is 2.57003, what is the relative mass excess?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [2.57003] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Could you work out the relative mass excess given mass excess = 2.57003?", + "a": "1.547708190067368e+27", + "valid": true, + "kind": "compute", + "expect": 1.547708190067368e+27, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [2.57003] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "I need the relative mass excess for a mass excess of 48.921, please.", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [48.920991] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "If the mass excess is 48.921, what is the relative mass excess?", + "a": "2.9460909317947517e+28", + "valid": true, + "kind": "compute", + "expect": 2.9460909317947517e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [48.920991] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Could you work out the relative mass excess given mass excess = 0.348438?", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [0.348438] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "I need the relative mass excess for a mass excess of 0.348438, please.", + "a": "2.0983406933235613e+26", + "valid": true, + "kind": "compute", + "expect": 2.0983406933235613e+26, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [0.348438] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "If the mass excess is 252.709, what is the relative mass excess?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [252.709024] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Could you work out the relative mass excess given mass excess = 252.709?", + "a": "1.521849315878826e+29", + "valid": true, + "kind": "compute", + "expect": 1.521849315878826e+29, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [252.709024] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "I need the relative mass excess for a mass excess of 20.3966, please.", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [20.396558] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "If the mass excess is 20.3966, what is the relative mass excess?", + "a": "1.2283094310889024e+28", + "valid": true, + "kind": "compute", + "expect": 1.2283094310889024e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [20.396558] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "Could you work out the relative mass excess given mass excess = 134.993?", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [134.992958] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "I need the relative mass excess for a mass excess of 134.993, please.", + "a": "8.129465924408498e+28", + "valid": true, + "kind": "compute", + "expect": 8.129465924408498e+28, + "dtype": "quantity", + "unit": "1", + "why": "relative mass excess for [134.992958] (the system relative mass excess (Wikidata Q98038610))" + }, + { + "q": "I need the relative mass excess, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass excess is not given" + }, + { + "q": "Can you tell me the relative mass excess?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass excess is not given" + }, + { + "q": "Do you know the relative mass excess of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative mass excess of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative mass excess given mass excess = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass excess: no example had one" + }, + { + "q": "What is a typical relative mass excess?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-mass-excess/program.py b/root/organs10/physics/specialists/solved-relative-mass-excess/program.py new file mode 100644 index 0000000000000000000000000000000000000000..92d81ff0a8f310642d8be98d5f1930f61bf26eb0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-excess/program.py @@ -0,0 +1,7 @@ +"""relative mass excess from mass excess (relative mass excess (Wikidata Q98038610)) +The maths organ (systems.py): solved from the system q0 = ((q2)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass_excess): + return 6.02214076208112e+26*mass_excess diff --git a/root/organs10/physics/specialists/solved-relative-mass-excess/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-mass-excess/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-excess/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/panel.json b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..dde4477f3e56e5389af4bcdf833ec705e3f3e5c5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 107.961 and mixing ratio 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [107.960666, 59.4105] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 107.961 and mixing ratio of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [107.960666, 59.4105] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 169.527 and mixing ratio 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [169.526958, 280.773702] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 169.527 and mixing ratio of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [169.526958, 280.773702] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 1.91195 and mixing ratio 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [1.911952, 82.240072] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 1.91195 and mixing ratio of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [1.911952, 82.240072] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 1.64379 and mixing ratio 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [1.643795, 252.709024] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 1.64379 and mixing ratio of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [1.643795, 252.709024] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 18.3169 and mixing ratio 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [18.316867, 6.838598] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 18.3169 and mixing ratio of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [18.316867, 6.838598] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 156.502 and mixing ratio 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [156.50181, 185.886273] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 156.502 and mixing ratio of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [156.50181, 185.886273] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the relative mass ratio of vapour for mass ratio of water vapour to dry gas at saturation 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mixing ratio is not given" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mixing ratio is not given" + }, + { + "q": "What is the relative mass ratio of vapour of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative mass ratio of vapour of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative mass ratio of vapour with mass ratio of water vapour to dry gas at saturation of -1.91195 and mixing ratio of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass ratio of water vapour to dry gas at saturation: no example had one" + }, + { + "q": "Which relative mass ratio of vapour is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the mass ratio of water vapour to dry gas at saturation is 8.50728 and the mixing ratio is 17.7888, what is the relative mass ratio of vapour?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [8.507283, 17.788778] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = 8.50728, mixing ratio = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [8.507283, 17.788778] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the relative mass ratio of vapour for a mass ratio of water vapour to dry gas at saturation of 8.24951 and a mixing ratio of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [8.24951, 0.634021] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "If the mass ratio of water vapour to dry gas at saturation is 8.24951 and the mixing ratio is 0.634021, what is the relative mass ratio of vapour?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [8.24951, 0.634021] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = 0.318734, mixing ratio = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [0.318734, 9.566071] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the relative mass ratio of vapour for a mass ratio of water vapour to dry gas at saturation of 0.318734 and a mixing ratio of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [0.318734, 9.566071] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "If the mass ratio of water vapour to dry gas at saturation is 0.671697 and the mixing ratio is 14.2496, what is the relative mass ratio of vapour?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [0.671697, 14.249569] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = 0.671697, mixing ratio = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [0.671697, 14.249569] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the relative mass ratio of vapour for a mass ratio of water vapour to dry gas at saturation of 21.7931 and a mixing ratio of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [21.793126, 29.510609] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "If the mass ratio of water vapour to dry gas at saturation is 21.7931 and the mixing ratio is 29.5106, what is the relative mass ratio of vapour?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [21.793126, 29.510609] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = 153.15, mixing ratio = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [153.149965, 18.595315] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the relative mass ratio of vapour for a mass ratio of water vapour to dry gas at saturation of 153.15 and a mixing ratio of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative mass ratio of vapour for [153.149965, 18.595315] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "If the mass ratio of water vapour to dry gas at saturation is 8.50728, what is the relative mass ratio of vapour?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mixing ratio is not given" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mixing ratio is not given" + }, + { + "q": "Do you know the relative mass ratio of vapour of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative mass ratio of vapour of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative mass ratio of vapour given mass ratio of water vapour to dry gas at saturation = -0.318734, mixing ratio = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass ratio of water vapour to dry gas at saturation: no example had one" + }, + { + "q": "What is a typical relative mass ratio of vapour?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/program.py b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/program.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b1e58cf16262bf4284d44c92ffe951707487dd --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/program.py @@ -0,0 +1,7 @@ +"""relative mass ratio of vapour from mass ratio of water vapour to dry gas at saturation, mixing ratio (relative mass ratio of vapour (Wikidata Q76379414)) +The maths organ (systems.py): solved from the system q1 = q2 / q0; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass_ratio_of_water_vapour_to_dry_gas_at_saturation, mixing_ratio): + return 1.0*mixing_ratio/mass_ratio_of_water_vapour_to_dry_gas_at_saturation diff --git a/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-mass-ratio-of-vapour/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-velocity-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-velocity-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-velocity-2/panel.json b/root/organs10/physics/specialists/solved-relative-velocity-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f9b2e20cee97824353668f89bab40deae7a07716 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative velocity for relativistic beta 107.961?", + "a": "23751346495.791645", + "valid": true, + "kind": "compute", + "expect": 23751346495.791645, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [107.960666] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 107.961.", + "a": "23751346495.791645", + "valid": true, + "kind": "compute", + "expect": 23751346495.791645, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [107.960666] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity for relativistic beta 22.652?", + "a": "4983445015.308274", + "valid": true, + "kind": "compute", + "expect": 4983445015.308274, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [22.652023] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 22.652.", + "a": "4983445015.308274", + "valid": true, + "kind": "compute", + "expect": 4983445015.308274, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [22.652023] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity for relativistic beta 173.394?", + "a": "38146600449.16655", + "valid": true, + "kind": "compute", + "expect": 38146600449.16655, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [173.393638] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 173.394.", + "a": "38146600449.16655", + "valid": true, + "kind": "compute", + "expect": 38146600449.16655, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [173.393638] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity for relativistic beta 126.709?", + "a": "27876035396.040123", + "valid": true, + "kind": "compute", + "expect": 27876035396.040123, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [126.709252] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 126.709.", + "a": "27876035396.040123", + "valid": true, + "kind": "compute", + "expect": 27876035396.040123, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [126.709252] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity for relativistic beta 0.671697?", + "a": "147773383.95472258", + "valid": true, + "kind": "compute", + "expect": 147773383.95472258, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [0.671697] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 0.671697.", + "a": "147773383.95472258", + "valid": true, + "kind": "compute", + "expect": 147773383.95472258, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [0.671697] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity for relativistic beta 1.16997?", + "a": "257392961.31514588", + "valid": true, + "kind": "compute", + "expect": 257392961.31514588, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [1.169968] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relative velocity with relativistic beta of 1.16997.", + "a": "257392961.31514588", + "valid": true, + "kind": "compute", + "expect": 257392961.31514588, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [1.169968] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relative velocity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relativistic beta is not given" + }, + { + "q": "Could you work out the relative velocity, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relativistic beta is not given" + }, + { + "q": "What is the relative velocity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative velocity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative velocity with relativistic beta of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relativistic beta: no example had one" + }, + { + "q": "Which relative velocity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the relativistic beta is 2.57003, what is the relative velocity?", + "a": "565406580.9268016", + "valid": true, + "kind": "compute", + "expect": 565406580.9268016, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [2.57003] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relative velocity given relativistic beta = 2.57003?", + "a": "565406580.9268016", + "valid": true, + "kind": "compute", + "expect": 565406580.9268016, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [2.57003] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relative velocity for a relativistic beta of 48.921, please.", + "a": "10762617989.202604", + "valid": true, + "kind": "compute", + "expect": 10762617989.202604, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [48.920991] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relativistic beta is 48.921, what is the relative velocity?", + "a": "10762617989.202604", + "valid": true, + "kind": "compute", + "expect": 10762617989.202604, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [48.920991] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relative velocity given relativistic beta = 0.348438?", + "a": "76656287.3186067", + "valid": true, + "kind": "compute", + "expect": 76656287.3186067, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [0.348438] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relative velocity for a relativistic beta of 0.348438, please.", + "a": "76656287.3186067", + "valid": true, + "kind": "compute", + "expect": 76656287.3186067, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [0.348438] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relativistic beta is 252.709, what is the relative velocity?", + "a": "55595985334.89606", + "valid": true, + "kind": "compute", + "expect": 55595985334.89606, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [252.709024] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relative velocity given relativistic beta = 252.709?", + "a": "55595985334.89606", + "valid": true, + "kind": "compute", + "expect": 55595985334.89606, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [252.709024] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relative velocity for a relativistic beta of 20.3966, please.", + "a": "4487242751.631956", + "valid": true, + "kind": "compute", + "expect": 4487242751.631956, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [20.396558] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relativistic beta is 20.3966, what is the relative velocity?", + "a": "4487242751.631956", + "valid": true, + "kind": "compute", + "expect": 4487242751.631956, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [20.396558] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relative velocity given relativistic beta = 134.993?", + "a": "29698450667.76236", + "valid": true, + "kind": "compute", + "expect": 29698450667.76236, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [134.992958] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relative velocity for a relativistic beta of 134.993, please.", + "a": "29698450667.76236", + "valid": true, + "kind": "compute", + "expect": 29698450667.76236, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [134.992958] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relative velocity, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relativistic beta is not given" + }, + { + "q": "Can you tell me the relative velocity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relativistic beta is not given" + }, + { + "q": "Do you know the relative velocity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative velocity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative velocity given relativistic beta = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relativistic beta: no example had one" + }, + { + "q": "What is a typical relative velocity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-velocity-2/program.py b/root/organs10/physics/specialists/solved-relative-velocity-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6f214b09c0832398e3164d5a4c343a1223e041 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity-2/program.py @@ -0,0 +1,7 @@ +"""relative velocity from relativistic beta (relativistic beta (Wikidata Q4897242)) +The maths organ (systems.py): solved from the system q0 = q1 / q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(relativistic_beta): + return 220000000.0*relativistic_beta diff --git a/root/organs10/physics/specialists/solved-relative-velocity-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-velocity-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-velocity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-velocity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-velocity/panel.json b/root/organs10/physics/specialists/solved-relative-velocity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..479267970150eb3f309720ef9a02a22e4df30255 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative velocity for velocity 107.961 and transitional velocity 59.4105?", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [107.960666, 59.4105] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 107.961 and transitional velocity of 59.4105.", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [107.960666, 59.4105] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 157.223 and transitional velocity 35.6412?", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [157.22256, 35.641157] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 157.223 and transitional velocity of 35.6412.", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [157.22256, 35.641157] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 126.709 and transitional velocity 1.70503?", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [126.709252, 1.705032] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 126.709 and transitional velocity of 1.70503.", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [126.709252, 1.705032] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 41.6566 and transitional velocity 13.8779?", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [41.656639, 13.877867] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 41.6566 and transitional velocity of 13.8779.", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [41.656639, 13.877867] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 8.50341 and transitional velocity 0.58813?", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [8.503407, 0.58813] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 8.50341 and transitional velocity of 0.58813.", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [8.503407, 0.58813] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 223.509 and transitional velocity 17.3414?", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [223.508796, 17.341435] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Tell me the relative velocity with velocity of 223.509 and transitional velocity of 17.3414.", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [223.508796, 17.341435] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "What is the relative velocity for velocity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the transitional velocity is not given" + }, + { + "q": "Tell me the relative velocity with velocity of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the transitional velocity is not given" + }, + { + "q": "What is the relative velocity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative velocity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative velocity with velocity of -126.709 and transitional velocity of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative velocity: no example had one" + }, + { + "q": "Which relative velocity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the velocity is 167.625 and the transitional velocity is 10.3291, what is the relative velocity?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [167.624948, 10.329054] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Could you work out the relative velocity given velocity = 167.625, transitional velocity = 10.3291?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [167.624948, 10.329054] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "I need the relative velocity for a velocity of 13.999 and a transitional velocity of 0.348438, please.", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [13.999029, 0.348438] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "If the velocity is 13.999 and the transitional velocity is 0.348438, what is the relative velocity?", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [13.999029, 0.348438] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Could you work out the relative velocity given velocity = 81.1967, transitional velocity = 6.98086?", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [81.196705, 6.980857] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "I need the relative velocity for a velocity of 81.1967 and a transitional velocity of 6.98086, please.", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [81.196705, 6.980857] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "If the velocity is 19.4474 and the transitional velocity is 4.51548, what is the relative velocity?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [19.447357, 4.515475] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Could you work out the relative velocity given velocity = 19.4474, transitional velocity = 4.51548?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [19.447357, 4.515475] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "I need the relative velocity for a velocity of 13.2373 and a transitional velocity of 4.71941, please.", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [13.237311, 4.719415] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "If the velocity is 13.2373 and the transitional velocity is 4.71941, what is the relative velocity?", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [13.237311, 4.719415] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "Could you work out the relative velocity given velocity = 21.7946, transitional velocity = 9.1061?", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [21.794621, 9.106104] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "I need the relative velocity for a velocity of 21.7946 and a transitional velocity of 9.1061, please.", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "m/s", + "why": "relative velocity for [21.794621, 9.106104] (the system composite motion (Wikidata Q105882582))" + }, + { + "q": "If the velocity is 167.625, what is the relative velocity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the transitional velocity is not given" + }, + { + "q": "Could you work out the relative velocity given velocity = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the transitional velocity is not given" + }, + { + "q": "Do you know the relative velocity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative velocity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative velocity given velocity = -81.1967, transitional velocity = 6.98086?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative velocity: no example had one" + }, + { + "q": "What is a typical relative velocity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-velocity/program.py b/root/organs10/physics/specialists/solved-relative-velocity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..eff2a52dff1ec57e14d1037f63908f31310ae295 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity/program.py @@ -0,0 +1,7 @@ +"""relative velocity from velocity, transitional velocity (composite motion (Wikidata Q105882582)) +The maths organ (systems.py): solved from the system q0 = q1 + q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(velocity, transitional_velocity): + return -1.0*transitional_velocity + 1.0*velocity diff --git a/root/organs10/physics/specialists/solved-relative-velocity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-velocity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-velocity/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relative-viscosity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relative-viscosity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-viscosity/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relative-viscosity/panel.json b/root/organs10/physics/specialists/solved-relative-viscosity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..19685e0eabc18c7a3fc9eaab79f49dcca426af32 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-viscosity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relative viscosity for viscosity of solvent 107.961 and viscosity of solution 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [107.960666, 59.4105] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 107.961 and viscosity of solution of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [107.960666, 59.4105] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 169.527 and viscosity of solution 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [169.526958, 280.773702] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 169.527 and viscosity of solution of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [169.526958, 280.773702] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 1.91195 and viscosity of solution 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [1.911952, 82.240072] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 1.91195 and viscosity of solution of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [1.911952, 82.240072] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 1.64379 and viscosity of solution 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [1.643795, 252.709024] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 1.64379 and viscosity of solution of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [1.643795, 252.709024] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 18.3169 and viscosity of solution 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [18.316867, 6.838598] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 18.3169 and viscosity of solution of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [18.316867, 6.838598] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 156.502 and viscosity of solution 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [156.50181, 185.886273] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 156.502 and viscosity of solution of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [156.50181, 185.886273] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "What is the relative viscosity for viscosity of solvent 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the viscosity of solution is not given" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the viscosity of solution is not given" + }, + { + "q": "What is the relative viscosity of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relative viscosity of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relative viscosity with viscosity of solvent of -1.91195 and viscosity of solution of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative viscosity of solvent: no example had one" + }, + { + "q": "Which relative viscosity is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the viscosity of solvent is 8.50728 and the viscosity of solution is 17.7888, what is the relative viscosity?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [8.507283, 17.788778] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = 8.50728, viscosity of solution = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [8.507283, 17.788778] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "I need the relative viscosity for a viscosity of solvent of 8.24951 and a viscosity of solution of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [8.24951, 0.634021] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "If the viscosity of solvent is 8.24951 and the viscosity of solution is 0.634021, what is the relative viscosity?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [8.24951, 0.634021] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = 0.318734, viscosity of solution = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [0.318734, 9.566071] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "I need the relative viscosity for a viscosity of solvent of 0.318734 and a viscosity of solution of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [0.318734, 9.566071] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "If the viscosity of solvent is 0.671697 and the viscosity of solution is 14.2496, what is the relative viscosity?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [0.671697, 14.249569] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = 0.671697, viscosity of solution = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [0.671697, 14.249569] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "I need the relative viscosity for a viscosity of solvent of 21.7931 and a viscosity of solution of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [21.793126, 29.510609] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "If the viscosity of solvent is 21.7931 and the viscosity of solution is 29.5106, what is the relative viscosity?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [21.793126, 29.510609] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = 153.15, viscosity of solution = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [153.149965, 18.595315] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "I need the relative viscosity for a viscosity of solvent of 153.15 and a viscosity of solution of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "relative viscosity for [153.149965, 18.595315] (the system relative viscosity (Wikidata Q7310812))" + }, + { + "q": "If the viscosity of solvent is 8.50728, what is the relative viscosity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the viscosity of solution is not given" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the viscosity of solution is not given" + }, + { + "q": "Do you know the relative viscosity of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relative viscosity of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relative viscosity given viscosity of solvent = -0.318734, viscosity of solution = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative viscosity of solvent: no example had one" + }, + { + "q": "What is a typical relative viscosity?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relative-viscosity/program.py b/root/organs10/physics/specialists/solved-relative-viscosity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4713bcb79b72d81b22491a31041882b7b69a5b27 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-viscosity/program.py @@ -0,0 +1,7 @@ +"""relative viscosity from viscosity of solvent, viscosity of solution (relative viscosity (Wikidata Q7310812)) +The maths organ (systems.py): solved from the system q0 = ((q2)/(q1)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(viscosity_of_solvent, viscosity_of_solution): + return 1.0*viscosity_of_solution/viscosity_of_solvent diff --git a/root/organs10/physics/specialists/solved-relative-viscosity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relative-viscosity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relative-viscosity/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relativistic-beta/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relativistic-beta/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relativistic-beta/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relativistic-beta/panel.json b/root/organs10/physics/specialists/solved-relativistic-beta/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..1feacfaf77a7af85d5c2a782d42d890ff5df5a93 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relativistic-beta/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relativistic beta for relative velocity 107.961?", + "a": "4.907302994998279e-07", + "valid": true, + "kind": "compute", + "expect": 4.907302994998279e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [107.960666] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 107.961.", + "a": "4.907302994998279e-07", + "valid": true, + "kind": "compute", + "expect": 4.907302994998279e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [107.960666] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta for relative velocity 22.652?", + "a": "1.0296373998570826e-07", + "valid": true, + "kind": "compute", + "expect": 1.0296373998570826e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [22.652023] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 22.652.", + "a": "1.0296373998570826e-07", + "valid": true, + "kind": "compute", + "expect": 1.0296373998570826e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [22.652023] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta for relative velocity 173.394?", + "a": "7.88152901842285e-07", + "valid": true, + "kind": "compute", + "expect": 7.88152901842285e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [173.393638] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 173.394.", + "a": "7.88152901842285e-07", + "valid": true, + "kind": "compute", + "expect": 7.88152901842285e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [173.393638] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta for relative velocity 126.709?", + "a": "5.759511445462841e-07", + "valid": true, + "kind": "compute", + "expect": 5.759511445462841e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [126.709252] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 126.709.", + "a": "5.759511445462841e-07", + "valid": true, + "kind": "compute", + "expect": 5.759511445462841e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [126.709252] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta for relative velocity 0.671697?", + "a": "3.05316908997361e-09", + "valid": true, + "kind": "compute", + "expect": 3.05316908997361e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [0.671697] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 0.671697.", + "a": "3.05316908997361e-09", + "valid": true, + "kind": "compute", + "expect": 3.05316908997361e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [0.671697] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta for relative velocity 1.16997?", + "a": "5.318036390808805e-09", + "valid": true, + "kind": "compute", + "expect": 5.318036390808805e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [1.169968] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Tell me the relativistic beta with relative velocity of 1.16997.", + "a": "5.318036390808805e-09", + "valid": true, + "kind": "compute", + "expect": 5.318036390808805e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [1.169968] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "What is the relativistic beta?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relative velocity is not given" + }, + { + "q": "Could you work out the relativistic beta, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relative velocity is not given" + }, + { + "q": "What is the relativistic beta of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relativistic beta of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relativistic beta with relative velocity of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relative velocity: no example had one" + }, + { + "q": "Which relativistic beta is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the relative velocity is 2.57003, what is the relativistic beta?", + "a": "1.1681954151380211e-08", + "valid": true, + "kind": "compute", + "expect": 1.1681954151380211e-08, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [2.57003] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relativistic beta given relative velocity = 2.57003?", + "a": "1.1681954151380211e-08", + "valid": true, + "kind": "compute", + "expect": 1.1681954151380211e-08, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [2.57003] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relativistic beta for a relative velocity of 48.921, please.", + "a": "2.223681402727813e-07", + "valid": true, + "kind": "compute", + "expect": 2.223681402727813e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [48.920991] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relative velocity is 48.921, what is the relativistic beta?", + "a": "2.223681402727813e-07", + "valid": true, + "kind": "compute", + "expect": 2.223681402727813e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [48.920991] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relativistic beta given relative velocity = 0.348438?", + "a": "1.583807589227413e-09", + "valid": true, + "kind": "compute", + "expect": 1.583807589227413e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [0.348438] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relativistic beta for a relative velocity of 0.348438, please.", + "a": "1.583807589227413e-09", + "valid": true, + "kind": "compute", + "expect": 1.583807589227413e-09, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [0.348438] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relative velocity is 252.709, what is the relativistic beta?", + "a": "1.148677382952399e-06", + "valid": true, + "kind": "compute", + "expect": 1.148677382952399e-06, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [252.709024] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relativistic beta given relative velocity = 252.709?", + "a": "1.148677382952399e-06", + "valid": true, + "kind": "compute", + "expect": 1.148677382952399e-06, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [252.709024] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relativistic beta for a relative velocity of 20.3966, please.", + "a": "9.271162709983391e-08", + "valid": true, + "kind": "compute", + "expect": 9.271162709983391e-08, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [20.396558] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "If the relative velocity is 20.3966, what is the relativistic beta?", + "a": "9.271162709983391e-08", + "valid": true, + "kind": "compute", + "expect": 9.271162709983391e-08, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [20.396558] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "Could you work out the relativistic beta given relative velocity = 134.993?", + "a": "6.136043526397188e-07", + "valid": true, + "kind": "compute", + "expect": 6.136043526397188e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [134.992958] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relativistic beta for a relative velocity of 134.993, please.", + "a": "6.136043526397188e-07", + "valid": true, + "kind": "compute", + "expect": 6.136043526397188e-07, + "dtype": "quantity", + "unit": "1", + "why": "relativistic beta for [134.992958] (the system relativistic beta (Wikidata Q4897242))" + }, + { + "q": "I need the relativistic beta, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relative velocity is not given" + }, + { + "q": "Can you tell me the relativistic beta?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relative velocity is not given" + }, + { + "q": "Do you know the relativistic beta of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relativistic beta of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relativistic beta given relative velocity = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relative velocity: no example had one" + }, + { + "q": "What is a typical relativistic beta?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relativistic-beta/program.py b/root/organs10/physics/specialists/solved-relativistic-beta/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d2c1931f803da8e5b88cae4e30b7070927215310 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relativistic-beta/program.py @@ -0,0 +1,7 @@ +"""relativistic beta from relative velocity (relativistic beta (Wikidata Q4897242)) +The maths organ (systems.py): solved from the system q0 = q1 / q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(relative_velocity): + return 4.54545454545455e-9*relative_velocity diff --git a/root/organs10/physics/specialists/solved-relativistic-beta/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relativistic-beta/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relativistic-beta/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relaxation-time-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relaxation-time-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relaxation-time-2/panel.json b/root/organs10/physics/specialists/solved-relaxation-time-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..df22afc258b258bc45771f454d43ace2aa899020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relaxation time for shear strain rate 107.961 and Weissenberg number 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [107.960666, 59.4105] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 107.961 and Weissenberg number of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [107.960666, 59.4105] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 169.527 and Weissenberg number 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [169.526958, 280.773702] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 169.527 and Weissenberg number of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [169.526958, 280.773702] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 1.91195 and Weissenberg number 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [1.911952, 82.240072] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 1.91195 and Weissenberg number of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [1.911952, 82.240072] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 1.64379 and Weissenberg number 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [1.643795, 252.709024] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 1.64379 and Weissenberg number of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [1.643795, 252.709024] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 18.3169 and Weissenberg number 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [18.316867, 6.838598] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 18.3169 and Weissenberg number of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [18.316867, 6.838598] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 156.502 and Weissenberg number 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [156.50181, 185.886273] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 156.502 and Weissenberg number of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [156.50181, 185.886273] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "What is the relaxation time for shear strain rate 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Weissenberg number is not given" + }, + { + "q": "Tell me the relaxation time with shear strain rate of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Weissenberg number is not given" + }, + { + "q": "What is the relaxation time of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relaxation time of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relaxation time with shear strain rate of -1.91195 and Weissenberg number of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative shear strain rate: no example had one" + }, + { + "q": "Which relaxation time is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the shear strain rate is 8.50728 and the Weissenberg number is 17.7888, what is the relaxation time?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [8.507283, 17.788778] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = 8.50728, Weissenberg number = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [8.507283, 17.788778] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "I need the relaxation time for a shear strain rate of 8.24951 and a Weissenberg number of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [8.24951, 0.634021] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "If the shear strain rate is 8.24951 and the Weissenberg number is 0.634021, what is the relaxation time?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [8.24951, 0.634021] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = 0.318734, Weissenberg number = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [0.318734, 9.566071] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "I need the relaxation time for a shear strain rate of 0.318734 and a Weissenberg number of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [0.318734, 9.566071] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "If the shear strain rate is 0.671697 and the Weissenberg number is 14.2496, what is the relaxation time?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [0.671697, 14.249569] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = 0.671697, Weissenberg number = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [0.671697, 14.249569] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "I need the relaxation time for a shear strain rate of 21.7931 and a Weissenberg number of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.793126, 29.510609] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "If the shear strain rate is 21.7931 and the Weissenberg number is 29.5106, what is the relaxation time?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.793126, 29.510609] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = 153.15, Weissenberg number = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [153.149965, 18.595315] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "I need the relaxation time for a shear strain rate of 153.15 and a Weissenberg number of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [153.149965, 18.595315] (the system Weissenberg number (Wikidata Q1753014))" + }, + { + "q": "If the shear strain rate is 8.50728, what is the relaxation time?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Weissenberg number is not given" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Weissenberg number is not given" + }, + { + "q": "Do you know the relaxation time of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relaxation time of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relaxation time given shear strain rate = -0.318734, Weissenberg number = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative shear strain rate: no example had one" + }, + { + "q": "What is a typical relaxation time?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relaxation-time-2/program.py b/root/organs10/physics/specialists/solved-relaxation-time-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..48452589e00092032894aefb95ad850b283ad45c --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time-2/program.py @@ -0,0 +1,7 @@ +"""relaxation time from shear strain rate, Weissenberg number (Weissenberg number (Wikidata Q1753014)) +The maths organ (systems.py): solved from the system q2 = q0*q1; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(shear_strain_rate, weissenberg_number): + return 1.0*weissenberg_number/shear_strain_rate diff --git a/root/organs10/physics/specialists/solved-relaxation-time-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relaxation-time-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-relaxation-time/organ_formula_v2.py b/root/organs10/physics/specialists/solved-relaxation-time/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-relaxation-time/panel.json b/root/organs10/physics/specialists/solved-relaxation-time/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..9fa43b6926925b8a46779408009a9d2b0822fcfc --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the relaxation time for elasticity number 107.961, kinematic viscosity 59.4105 and pipe radius 5.77717?", + "a": "60.65014321820282", + "valid": true, + "kind": "compute", + "expect": 60.65014321820282, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [107.960666, 59.4105, 5.777165] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 107.961, kinematic viscosity of 59.4105 and pipe radius of 5.77717.", + "a": "60.65014321820282", + "valid": true, + "kind": "compute", + "expect": 60.65014321820282, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [107.960666, 59.4105, 5.777165] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 85.2416, kinematic viscosity 160.878 and pipe radius 2.69428?", + "a": "3.846265616656069", + "valid": true, + "kind": "compute", + "expect": 3.846265616656069, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [85.241623, 160.878442, 2.69428] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 85.2416, kinematic viscosity of 160.878 and pipe radius of 2.69428.", + "a": "3.846265616656069", + "valid": true, + "kind": "compute", + "expect": 3.846265616656069, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [85.241623, 160.878442, 2.69428] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 45.6157, kinematic viscosity 4.97131 and pipe radius 94.305?", + "a": "81604.34728741873", + "valid": true, + "kind": "compute", + "expect": 81604.34728741873, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [45.61567, 4.971307, 94.305046] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 45.6157, kinematic viscosity of 4.97131 and pipe radius of 94.305.", + "a": "81604.34728741873", + "valid": true, + "kind": "compute", + "expect": 81604.34728741873, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [45.61567, 4.971307, 94.305046] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 10.5638, kinematic viscosity 198.839 and pipe radius 0.671697?", + "a": "0.02396997220671399", + "valid": true, + "kind": "compute", + "expect": 0.02396997220671399, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [10.563843, 198.838955, 0.671697] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 10.5638, kinematic viscosity of 198.839 and pipe radius of 0.671697.", + "a": "0.02396997220671399", + "valid": true, + "kind": "compute", + "expect": 0.02396997220671399, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [10.563843, 198.838955, 0.671697] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 21.7931, kinematic viscosity 29.5106 and pipe radius 8.50341?", + "a": "53.398286934776955", + "valid": true, + "kind": "compute", + "expect": 53.398286934776955, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.793126, 29.510609, 8.503407] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 21.7931, kinematic viscosity of 29.5106 and pipe radius of 8.50341.", + "a": "53.398286934776955", + "valid": true, + "kind": "compute", + "expect": 53.398286934776955, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.793126, 29.510609, 8.503407] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 223.509, kinematic viscosity 17.3414 and pipe radius 7.10705?", + "a": "651.0108507453602", + "valid": true, + "kind": "compute", + "expect": 651.0108507453602, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [223.508796, 17.341435, 7.107049] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the relaxation time with elasticity number of 223.509, kinematic viscosity of 17.3414 and pipe radius of 7.10705.", + "a": "651.0108507453602", + "valid": true, + "kind": "compute", + "expect": 651.0108507453602, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [223.508796, 17.341435, 7.107049] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the relaxation time for elasticity number 107.961 and kinematic viscosity 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pipe radius is not given" + }, + { + "q": "Tell me the relaxation time with elasticity number of 85.2416 and kinematic viscosity of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pipe radius is not given" + }, + { + "q": "What is the relaxation time of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the relaxation time of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the relaxation time with elasticity number of -45.6157, kinematic viscosity of 4.97131 and pipe radius of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative elasticity number: no example had one" + }, + { + "q": "Which relaxation time is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the elasticity number is 17.7888, kinematic viscosity is 167.625 and the pipe radius is 10.3291, what is the relaxation time?", + "a": "11.322142006979506", + "valid": true, + "kind": "compute", + "expect": 11.322142006979506, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [17.788778, 167.624948, 10.329054] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the relaxation time given elasticity number = 17.7888, kinematic viscosity = 167.625, pipe radius = 10.3291?", + "a": "11.322142006979506", + "valid": true, + "kind": "compute", + "expect": 11.322142006979506, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [17.788778, 167.624948, 10.329054] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the relaxation time for an elasticity number of 21.511, a kinematic viscosity of 173.394 and a pipe radius of 251.084, please.", + "a": "7821.066296015693", + "valid": true, + "kind": "compute", + "expect": 7821.066296015693, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.511016, 173.393638, 251.084037] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the elasticity number is 21.511, kinematic viscosity is 173.394 and the pipe radius is 251.084, what is the relaxation time?", + "a": "7821.066296015693", + "valid": true, + "kind": "compute", + "expect": 7821.066296015693, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [21.511016, 173.393638, 251.084037] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the relaxation time given elasticity number = 129.245, kinematic viscosity = 1.18359, pipe radius = 15.9416?", + "a": "27750.886778450953", + "valid": true, + "kind": "compute", + "expect": 27750.886778450953, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [129.244984, 1.18359, 15.941612] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the relaxation time for an elasticity number of 129.245, a kinematic viscosity of 1.18359 and a pipe radius of 15.9416, please.", + "a": "27750.886778450953", + "valid": true, + "kind": "compute", + "expect": 27750.886778450953, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [129.244984, 1.18359, 15.941612] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the elasticity number is 20.3966, kinematic viscosity is 18.3169 and the pipe radius is 6.8386, what is the relaxation time?", + "a": "52.07626748057164", + "valid": true, + "kind": "compute", + "expect": 52.07626748057164, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [20.396558, 18.316867, 6.838598] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the relaxation time given elasticity number = 20.3966, kinematic viscosity = 18.3169, pipe radius = 6.8386?", + "a": "52.07626748057164", + "valid": true, + "kind": "compute", + "expect": 52.07626748057164, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [20.396558, 18.316867, 6.838598] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the relaxation time for an elasticity number of 185.886, a kinematic viscosity of 13.2373 and a pipe radius of 4.71941, please.", + "a": "312.76910403880635", + "valid": true, + "kind": "compute", + "expect": 312.76910403880635, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [185.886273, 13.237311, 4.719415] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the elasticity number is 185.886, kinematic viscosity is 13.2373 and the pipe radius is 4.71941, what is the relaxation time?", + "a": "312.76910403880635", + "valid": true, + "kind": "compute", + "expect": 312.76910403880635, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [185.886273, 13.237311, 4.719415] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the relaxation time given elasticity number = 9.1061, kinematic viscosity = 24.5721, pipe radius = 108.451?", + "a": "4358.690568080156", + "valid": true, + "kind": "compute", + "expect": 4358.690568080156, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [9.106104, 24.572086, 108.450792] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the relaxation time for an elasticity number of 9.1061, a kinematic viscosity of 24.5721 and a pipe radius of 108.451, please.", + "a": "4358.690568080156", + "valid": true, + "kind": "compute", + "expect": 4358.690568080156, + "dtype": "quantity", + "unit": "s", + "why": "relaxation time for [9.106104, 24.572086, 108.450792] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the elasticity number is 17.7888 and the kinematic viscosity is 167.625, what is the relaxation time?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pipe radius is not given" + }, + { + "q": "Could you work out the relaxation time given elasticity number = 21.511, kinematic viscosity = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pipe radius is not given" + }, + { + "q": "Do you know the relaxation time of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the relaxation time of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the relaxation time given elasticity number = -129.245, kinematic viscosity = 1.18359, pipe radius = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative elasticity number: no example had one" + }, + { + "q": "What is a typical relaxation time?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-relaxation-time/program.py b/root/organs10/physics/specialists/solved-relaxation-time/program.py new file mode 100644 index 0000000000000000000000000000000000000000..948e18e140d61cebaa2c707f0f730b1637b8ca28 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time/program.py @@ -0,0 +1,7 @@ +"""relaxation time from elasticity number, kinematic viscosity, pipe radius (elasticity number (Wikidata Q102310770)) +The maths organ (systems.py): solved from the system q1 = ((q0*q2)/(q3 **(2))); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(elasticity_number, kinematic_viscosity, pipe_radius): + return 1.0*elasticity_number*pipe_radius**2/kinematic_viscosity diff --git a/root/organs10/physics/specialists/solved-relaxation-time/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-relaxation-time/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-relaxation-time/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-resistance-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-resistance-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance-2/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-resistance-2/panel.json b/root/organs10/physics/specialists/solved-resistance-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..1511c323617fd546bc23c8a53ed2ab534f93c5ef --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the resistance for power 107.961 and voltage 59.4105?", + "a": "32.6934583430848", + "valid": true, + "kind": "compute", + "expect": 32.6934583430848, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [107.960666, 59.4105] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 107.961 and voltage of 59.4105.", + "a": "32.6934583430848", + "valid": true, + "kind": "compute", + "expect": 32.6934583430848, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [107.960666, 59.4105] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 169.527 and voltage 280.774?", + "a": "465.02263030060664", + "valid": true, + "kind": "compute", + "expect": 465.02263030060664, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [169.526958, 280.773702] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 169.527 and voltage of 280.774.", + "a": "465.02263030060664", + "valid": true, + "kind": "compute", + "expect": 465.02263030060664, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [169.526958, 280.773702] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 1.91195 and voltage 82.2401?", + "a": "3537.4477262556725", + "valid": true, + "kind": "compute", + "expect": 3537.4477262556725, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.911952, 82.240072] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 1.91195 and voltage of 82.2401.", + "a": "3537.4477262556725", + "valid": true, + "kind": "compute", + "expect": 3537.4477262556725, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.911952, 82.240072] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 1.64379 and voltage 252.709?", + "a": "38850.24088259771", + "valid": true, + "kind": "compute", + "expect": 38850.24088259771, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.643795, 252.709024] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 1.64379 and voltage of 252.709.", + "a": "38850.24088259771", + "valid": true, + "kind": "compute", + "expect": 38850.24088259771, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.643795, 252.709024] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 18.3169 and voltage 6.8386?", + "a": "2.5531890026584962", + "valid": true, + "kind": "compute", + "expect": 2.5531890026584962, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [18.316867, 6.838598] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 18.3169 and voltage of 6.8386.", + "a": "2.5531890026584962", + "valid": true, + "kind": "compute", + "expect": 2.5531890026584962, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [18.316867, 6.838598] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 156.502 and voltage 185.886?", + "a": "220.78790309845184", + "valid": true, + "kind": "compute", + "expect": 220.78790309845184, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [156.50181, 185.886273] (the system Resistor power)" + }, + { + "q": "Tell me the resistance with power of 156.502 and voltage of 185.886.", + "a": "220.78790309845184", + "valid": true, + "kind": "compute", + "expect": 220.78790309845184, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [156.50181, 185.886273] (the system Resistor power)" + }, + { + "q": "What is the resistance for power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the voltage is not given" + }, + { + "q": "Tell me the resistance with power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the voltage is not given" + }, + { + "q": "What is the resistance of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the resistance of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the resistance with power of -1.91195 and voltage of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which resistance is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the power is 8.50728 and the voltage is 17.7888, what is the resistance?", + "a": "37.19643981970935", + "valid": true, + "kind": "compute", + "expect": 37.19643981970935, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.507283, 17.788778] (the system Resistor power)" + }, + { + "q": "Could you work out the resistance given power = 8.50728, voltage = 17.7888?", + "a": "37.19643981970935", + "valid": true, + "kind": "compute", + "expect": 37.19643981970935, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.507283, 17.788778] (the system Resistor power)" + }, + { + "q": "I need the resistance for a power of 8.24951 and a voltage of 0.634021, please.", + "a": "0.048728057845908244", + "valid": true, + "kind": "compute", + "expect": 0.048728057845908244, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.24951, 0.634021] (the system Resistor power)" + }, + { + "q": "If the power is 8.24951 and the voltage is 0.634021, what is the resistance?", + "a": "0.048728057845908244", + "valid": true, + "kind": "compute", + "expect": 0.048728057845908244, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.24951, 0.634021] (the system Resistor power)" + }, + { + "q": "Could you work out the resistance given power = 0.318734, voltage = 9.56607?", + "a": "287.10366788468673", + "valid": true, + "kind": "compute", + "expect": 287.10366788468673, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.318734, 9.566071] (the system Resistor power)" + }, + { + "q": "I need the resistance for a power of 0.318734 and a voltage of 9.56607, please.", + "a": "287.10366788468673", + "valid": true, + "kind": "compute", + "expect": 287.10366788468673, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.318734, 9.566071] (the system Resistor power)" + }, + { + "q": "If the power is 0.671697 and the voltage is 14.2496, what is the resistance?", + "a": "302.2942864015461", + "valid": true, + "kind": "compute", + "expect": 302.2942864015461, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.671697, 14.249569] (the system Resistor power)" + }, + { + "q": "Could you work out the resistance given power = 0.671697, voltage = 14.2496?", + "a": "302.2942864015461", + "valid": true, + "kind": "compute", + "expect": 302.2942864015461, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.671697, 14.249569] (the system Resistor power)" + }, + { + "q": "I need the resistance for a power of 21.7931 and a voltage of 29.5106, please.", + "a": "39.961041100999296", + "valid": true, + "kind": "compute", + "expect": 39.961041100999296, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [21.793126, 29.510609] (the system Resistor power)" + }, + { + "q": "If the power is 21.7931 and the voltage is 29.5106, what is the resistance?", + "a": "39.961041100999296", + "valid": true, + "kind": "compute", + "expect": 39.961041100999296, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [21.793126, 29.510609] (the system Resistor power)" + }, + { + "q": "Could you work out the resistance given power = 153.15, voltage = 18.5953?", + "a": "2.257824591404911", + "valid": true, + "kind": "compute", + "expect": 2.257824591404911, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [153.149965, 18.595315] (the system Resistor power)" + }, + { + "q": "I need the resistance for a power of 153.15 and a voltage of 18.5953, please.", + "a": "2.257824591404911", + "valid": true, + "kind": "compute", + "expect": 2.257824591404911, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [153.149965, 18.595315] (the system Resistor power)" + }, + { + "q": "If the power is 8.50728, what is the resistance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the voltage is not given" + }, + { + "q": "Could you work out the resistance given power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the voltage is not given" + }, + { + "q": "Do you know the resistance of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the resistance of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the resistance given power = -0.318734, voltage = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "What is a typical resistance?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-resistance-2/program.py b/root/organs10/physics/specialists/solved-resistance-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6841139f58c84336eed46b8407ab6f905bc4d42e --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance-2/program.py @@ -0,0 +1,7 @@ +"""resistance from power, voltage (Resistor power) +The maths organ (systems.py): solved from the system P = U**2/R; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(power, voltage): + return 1.0*voltage**2/power diff --git a/root/organs10/physics/specialists/solved-resistance-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-resistance-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance-2/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t) diff --git a/root/organs10/physics/specialists/solved-resistance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-resistance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance/organ_formula_v2.py @@ -0,0 +1,163 @@ +"""organ_formula_v2 - v1 + a question is declined as missing an input only when it names one of the inputs (v1 declined +"What is the largest living animal species that only eats plants?" for the zodiac program, whose output is "animal": +the gate found the core item made worse, 2026-10-20). A question that names the output and no input is not this +program's, and gets no reply. +v2 also keeps to the DOMAIN of its examples (spec.json "domain", written from the worked examples the composer saw): an +input every example gave as positive (or non-negative) must be so in the question, and an answer whose sign no example's +answer had is not given ("ABV for original gravity 1.010 and final gravity 1.050" would be -5.25): out_of_domain, an +in-domain refusal that says why. A program is evidence for the range its examples span in sign, not beyond. + +organ_formula_v1 - the GENERIC FORMULA SPECIALIST: one program the code composer wrote (program.py beside this file) and +the typed signature it was written for (spec.json: the inputs and the output, each a label with an optional unit in +parentheses). Built, not trained; no phrasing templates. + +Reading, by role: the output is named in the question (its label; when an input has the same label, the output's unit too, +"in F"); each input is its label with a value right after it ("original gravity 1.055", "age of 25", "f-number = 8") or +right before it ("1.055 original gravity"). A value is a number ("1,000", "0.5", "1/125") or, for an input whose examples +were codes, a token mixing digits and letters ("205/55R16"). + compute every input found: "The is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? is ." and the program it came from + missing_input a short direct question names the output but not every input's value: an in-domain refusal naming what + is missing +Narrowing (narrow_v1, the factory's shared rule): story-shaped and relational turns belong to the core; a turn carrying +numbers that no input claims is a different calculation and belongs to the core. Everything else: no reply.""" +from __future__ import annotations + +import importlib.util +import json +import os +import re + +from narrow_v1 import narrative, short_direct + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?" +CODE = r"[A-Za-z0-9]*\d[A-Za-z0-9]*[/\-][A-Za-z0-9/\-]*\d[A-Za-z0-9]*" +ANYNUM = re.compile(r"(? 0 if sign == "positive" else v >= 0 + + +def sign_of(values): + """the sign every example gave: "positive", "nonnegative" or "any" (text values: "any")""" + if not values or any(isinstance(v, str) for v in values): + return "any" + if all(v > 0 for v in values): + return "positive" + return "nonnegative" if all(v >= 0 for v in values) else "any" + + +def _fmt(v): + if isinstance(v, str): + return v + v = float(v) + if v == 0: + return "0" + return ("%.6g" % v) if 1e-3 <= abs(v) < 1e7 else ("%.4g" % v) + + +class FormulaOrgan: + def __init__(self, spec="spec.json"): + self.spec = json.load(open(os.path.join(HERE, spec), encoding="utf-8")) + loader = importlib.util.spec_from_file_location("composed_program", os.path.join(HERE, "program.py")) + mod = importlib.util.module_from_spec(loader) + loader.loader.exec_module(mod) + self.compute = mod.compute + self.out_label, self.out_unit = split_label(self.spec["output"]) + self.ins = [split_label(x) for x in self.spec["inputs"]] + self.kinds = self.spec["input_kinds"] # "number" or "code", from the examples + dom = self.spec.get("domain") or {} + self.in_sign = dom.get("inputs") or ["any"] * len(self.kinds) # "positive", "nonnegative" or "any", per input + self.out_sign = dom.get("output", "any") + collide = any(lab.lower() == self.out_label.lower() for lab, _ in self.ins) + out = label_rx(self.out_label) + if collide and self.out_unit: # "the temperature in F" + out += r"\s+(?:in|to)\s+(?:degrees\s+)?" + re.escape(self.out_unit) + r"(?![\w])" + self.rx_out = re.compile(out, re.I) + self.rx_in = [] + for (lab, unit), kind in zip(self.ins, self.kinds): + v = CODE if kind == "code" else NUM + after = re.compile(label_rx(lab) + LINK + r"(" + v + r")(?![\w/])", re.I) + before = re.compile(r"(? 120, 80)""" + out = {} + for i, (v, kind) in enumerate(zip(vals, self.kinds)): + if kind == "code": + for k, x in enumerate(re.findall(r"\d+(?:\.\d+)?", str(v))): + out[(i, k)] = float(x) + elif not isinstance(v, str): + out[(i, 0)] = float(v) + return out + + def _domain_v3(self, vals): + dom = self.spec.get("domain") or {} + comp = self._components(vals) + for o in dom.get("order") or []: + a, b = tuple(o["greater"]), tuple(o["lesser"]) + if a in comp and b in comp and not comp[a] > comp[b]: + return ("In every worked example this program was written from, the %s is greater than the %s; here it is not " + "(%s and %s), so it is not a reading I can work from." % (o["greater_name"], o["lesser_name"], + _fmt(comp[a]), _fmt(comp[b]))) + for f in dom.get("facts") or []: + x = comp.get((f["input"], 0)) + if x is None: + continue + bad = (f.get("integer") and x != int(x)) or ("min" in f and x < f["min"]) or ("max" in f and x > f["max"]) + if bad: + return "%s is not a possible %s: %s. So I won't compute it." % (_fmt(x), f["name"], f["why"]) + return None + + def answer(self, text, session_id="default"): + t = re.sub(r"\s+", " ", str(text or "")).strip() + if not self.rx_out.search(t) or narrative(t) or not ASKING.search(t): + return None + vals, missing, spans = self._read(t) + stray = [m for m in ANYNUM.finditer(t) if not any(a <= m.start() < b for a, b in spans)] + if stray: # numbers no input claims: another calculation + return None + if missing: + named = any(re.search(label_rx(lab), t, re.I) for lab, _ in self.ins) + if named and short_direct(t): + return {"kind": "missing_input", "status": "declined", + "response": "To work out the %s I need the %s, and the question doesn't give %s." + % (self.out_label, " and the ".join(missing), "it" if len(missing) == 1 else "them")} + return None + for (lab, _), v, sign in zip(self.ins, vals, self.in_sign): + if not _in_sign(v, sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "Every worked example this program was written from has a %s %s; %s is outside that, so I " + "won't extrapolate." % (sign.replace("nonnegative", "non-negative"), lab, _fmt(v))} + refused = self._domain_v3(vals) + if refused: + return {"kind": "out_of_domain", "status": "declined", "response": refused} + try: + y = self.compute(*vals) + except Exception: + return None + if y is None or (isinstance(y, float) and y != y): + return None + if not _in_sign(y, self.out_sign): + return {"kind": "out_of_domain", "status": "declined", + "response": "That would make the %s %s, and every worked example this program was written from gave a %s " + "one, so I won't give it." % (self.out_label, _fmt(y), self.out_sign.replace("nonnegative", "non-negative"))} + unit =(" " + self.out_unit) if self.out_unit and not isinstance(y, str) else "" + return {"kind": "compute", "status": "answered", + "response": "The %s is %s%s. (A composed program: %s; %s.)" % (self.out_label, _fmt(y), unit, + self.spec["expression"], self.spec["said"])} diff --git a/root/organs10/physics/specialists/solved-resistance/panel.json b/root/organs10/physics/specialists/solved-resistance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c2a97aea67dfe6a930daded5f04e66cc43be7227 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the resistance for voltage 107.961 and current 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [107.960666, 59.4105] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 107.961 and current of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [107.960666, 59.4105] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 169.527 and current 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [169.526958, 280.773702] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 169.527 and current of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [169.526958, 280.773702] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 1.91195 and current 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.911952, 82.240072] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 1.91195 and current of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.911952, 82.240072] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 1.64379 and current 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.643795, 252.709024] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 1.64379 and current of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [1.643795, 252.709024] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 18.3169 and current 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [18.316867, 6.838598] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 18.3169 and current of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [18.316867, 6.838598] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 156.502 and current 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [156.50181, 185.886273] (the system Ohm's law)" + }, + { + "q": "Tell me the resistance with voltage of 156.502 and current of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [156.50181, 185.886273] (the system Ohm's law)" + }, + { + "q": "What is the resistance for voltage 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Tell me the resistance with voltage of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "What is the resistance of the Eiffel Tower?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "What is the resistance of Mount Everest?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Tell me the resistance with voltage of -1.91195 and current of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "Which resistance is the most common?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ], + "heldout": [ + { + "q": "If the voltage is 8.50728 and the current is 17.7888, what is the resistance?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.507283, 17.788778] (the system Ohm's law)" + }, + { + "q": "Could you work out the resistance given voltage = 8.50728, current = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.507283, 17.788778] (the system Ohm's law)" + }, + { + "q": "I need the resistance for a voltage of 8.24951 and a current of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.24951, 0.634021] (the system Ohm's law)" + }, + { + "q": "If the voltage is 8.24951 and the current is 0.634021, what is the resistance?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [8.24951, 0.634021] (the system Ohm's law)" + }, + { + "q": "Could you work out the resistance given voltage = 0.318734, current = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.318734, 9.566071] (the system Ohm's law)" + }, + { + "q": "I need the resistance for a voltage of 0.318734 and a current of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.318734, 9.566071] (the system Ohm's law)" + }, + { + "q": "If the voltage is 0.671697 and the current is 14.2496, what is the resistance?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.671697, 14.249569] (the system Ohm's law)" + }, + { + "q": "Could you work out the resistance given voltage = 0.671697, current = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [0.671697, 14.249569] (the system Ohm's law)" + }, + { + "q": "I need the resistance for a voltage of 21.7931 and a current of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [21.793126, 29.510609] (the system Ohm's law)" + }, + { + "q": "If the voltage is 21.7931 and the current is 29.5106, what is the resistance?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [21.793126, 29.510609] (the system Ohm's law)" + }, + { + "q": "Could you work out the resistance given voltage = 153.15, current = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [153.149965, 18.595315] (the system Ohm's law)" + }, + { + "q": "I need the resistance for a voltage of 153.15 and a current of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "ohm", + "why": "resistance for [153.149965, 18.595315] (the system Ohm's law)" + }, + { + "q": "If the voltage is 8.50728, what is the resistance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Could you work out the resistance given voltage = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the current is not given" + }, + { + "q": "Do you know the resistance of a violin?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Do you know the resistance of the French Revolution?", + "a": "", + "valid": false, + "kind": "not_held", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a named thing, not inputs: a lookup the program cannot do" + }, + { + "q": "Could you work out the resistance given voltage = -0.318734, current = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative voltage: no example had one" + }, + { + "q": "What is a typical resistance?", + "a": "", + "valid": false, + "kind": "output_only", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "names the output and no input: not this program's" + } + ] +} \ No newline at end of file diff --git a/root/organs10/physics/specialists/solved-resistance/program.py b/root/organs10/physics/specialists/solved-resistance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5c9ac8e1296557a8b7c9dbcfb49697533196b941 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance/program.py @@ -0,0 +1,7 @@ +"""resistance from voltage, current (Ohm's law) +The maths organ (systems.py): solved from the system U = I*R; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(voltage, current): + return 1.0*voltage/current diff --git a/root/organs10/physics/specialists/solved-resistance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-resistance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-resistance/scorer_formula_v1.py @@ -0,0 +1,31 @@ +"""scorer_formula_v1 - scorer for composed formula specialists: (good, asserted). +A must-decline item answered is a false yes. A valid quantity item is right when the FIRST number in the reply (the +answer, before any working) is within 0.5% of the sealed answer; a valid text item is right when the answer appears in the +reply as a whole word, exactly as written.""" +import re + + +def _first_num(text): + m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:[eE][+-]?\d+)?", text) + if not m: + return None + try: + return float(m.group(0).replace(",", "")) + except ValueError: + return None + + +def ok(p, r): + r = r or {} + text = str(r.get("response", "")) + answered = str(r.get("status", "")) == "answered" + if not p["valid"]: + return (not answered), answered + if not answered: + return False, False + if p.get("dtype") == "quantity": + want, got = float(p["expect"]), _first_num(text) + if got is None: + return False, True + return abs(got - want) <= (0.005 * abs(want) if want else 0.005), True + return re.search(r"(?= 3 or len(t.split()) > 40 or RELATION.search(t) is not None or RATE.search(t) is not None + + +def short_direct(t): + """a direct question an organ may decline: at most 2 sentences, at most 25 words, not narrative""" + t = str(t or "") + return sentences(t) <= 2 and len(t.split()) <= 25 and not narrative(t)