diff --git a/root/organs10/physics/specialists/solved-mean-free-time/narrow_v1.py b/root/organs10/physics/specialists/solved-mean-free-time/narrow_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..647d4d5e961acd006c9de30f0ce8b0b8f5139cda --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-free-time/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-mean-free-time/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mean-free-time/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-free-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-mean-free-time/panel.json b/root/organs10/physics/specialists/solved-mean-free-time/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c4d5e0446d5be9c76f45a372509210d9bfcf4085 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-free-time/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mean free time for average particle speed 107.961 and mean free path 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [107.960666, 59.4105] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 107.961 and mean free path of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [107.960666, 59.4105] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 169.527 and mean free path 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [169.526958, 280.773702] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 169.527 and mean free path of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [169.526958, 280.773702] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 1.91195 and mean free path 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [1.911952, 82.240072] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 1.91195 and mean free path of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [1.911952, 82.240072] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 1.64379 and mean free path 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [1.643795, 252.709024] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 1.64379 and mean free path of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [1.643795, 252.709024] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 18.3169 and mean free path 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [18.316867, 6.838598] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 18.3169 and mean free path of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [18.316867, 6.838598] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 156.502 and mean free path 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [156.50181, 185.886273] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Tell me the mean free time with average particle speed of 156.502 and mean free path of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [156.50181, 185.886273] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "What is the mean free time for average particle speed 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mean free path is not given" + }, + { + "q": "Tell me the mean free time with average particle speed of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mean free path is not given" + }, + { + "q": "What is the mean free 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 mean free 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 mean free time with average particle speed of -1.91195 and mean free path of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative average particle speed: no example had one" + }, + { + "q": "Which mean free 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 average particle speed is 8.50728 and the mean free path is 17.7888, what is the mean free time?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [8.507283, 17.788778] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Could you work out the mean free time given average particle speed = 8.50728, mean free path = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [8.507283, 17.788778] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "I need the mean free time for an average particle speed of 8.24951 and a mean free path of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [8.24951, 0.634021] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "If the average particle speed is 8.24951 and the mean free path is 0.634021, what is the mean free time?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [8.24951, 0.634021] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Could you work out the mean free time given average particle speed = 0.318734, mean free path = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [0.318734, 9.566071] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "I need the mean free time for an average particle speed of 0.318734 and a mean free path of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [0.318734, 9.566071] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "If the average particle speed is 0.671697 and the mean free path is 14.2496, what is the mean free time?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [0.671697, 14.249569] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Could you work out the mean free time given average particle speed = 0.671697, mean free path = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [0.671697, 14.249569] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "I need the mean free time for an average particle speed of 21.7931 and a mean free path of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [21.793126, 29.510609] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "If the average particle speed is 21.7931 and the mean free path is 29.5106, what is the mean free time?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [21.793126, 29.510609] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "Could you work out the mean free time given average particle speed = 153.15, mean free path = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [153.149965, 18.595315] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "I need the mean free time for an average particle speed of 153.15 and a mean free path of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s", + "why": "mean free time for [153.149965, 18.595315] (the system mean free time (Wikidata Q1940665))" + }, + { + "q": "If the average particle speed is 8.50728, what is the mean free time?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mean free path is not given" + }, + { + "q": "Could you work out the mean free time given average particle speed = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mean free path is not given" + }, + { + "q": "Do you know the mean free 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 mean free 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 mean free time given average particle speed = -0.318734, mean free path = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative average particle speed: no example had one" + }, + { + "q": "What is a typical mean free 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-mean-free-time/program.py b/root/organs10/physics/specialists/solved-mean-free-time/program.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfc0749c2728adf9116c0bd76bdc98c3704a7c7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-free-time/program.py @@ -0,0 +1,7 @@ +"""mean free time from average particle speed, mean free path (mean free time (Wikidata Q1940665)) +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(average_particle_speed, mean_free_path): + return 1.0*mean_free_path/average_particle_speed diff --git a/root/organs10/physics/specialists/solved-mean-free-time/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mean-free-time/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-free-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-mean-lifetime-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mean-lifetime-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime-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-mean-lifetime-2/panel.json b/root/organs10/physics/specialists/solved-mean-lifetime-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..77e6c1a7fd4734218d38c1e313d05b3790148033 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mean lifetime for decay constant 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [107.960666] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [107.960666] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime for decay constant 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [22.652023] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [22.652023] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime for decay constant 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [173.393638] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [173.393638] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime for decay constant 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [126.709252] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [126.709252] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime for decay constant 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.671697] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.671697] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime for decay constant 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.169968] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Tell me the mean lifetime with decay constant of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.169968] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "What is the mean lifetime?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the decay constant is not given" + }, + { + "q": "Could you work out the mean lifetime, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the decay constant is not given" + }, + { + "q": "What is the mean lifetime 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 mean lifetime 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 mean lifetime with decay constant of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative decay constant: no example had one" + }, + { + "q": "Which mean lifetime 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 decay constant is 2.57003, what is the mean lifetime?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [2.57003] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Could you work out the mean lifetime given decay constant = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [2.57003] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "I need the mean lifetime for a decay constant of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [48.920991] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "If the decay constant is 48.921, what is the mean lifetime?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [48.920991] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Could you work out the mean lifetime given decay constant = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.348438] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "I need the mean lifetime for a decay constant of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.348438] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "If the decay constant is 252.709, what is the mean lifetime?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [252.709024] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Could you work out the mean lifetime given decay constant = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [252.709024] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "I need the mean lifetime for a decay constant of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [20.396558] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "If the decay constant is 20.3966, what is the mean lifetime?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [20.396558] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "Could you work out the mean lifetime given decay constant = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [134.992958] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "I need the mean lifetime for a decay constant of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [134.992958] (the system mean lifetime (Wikidata Q1758559))" + }, + { + "q": "I need the mean lifetime, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the decay constant is not given" + }, + { + "q": "Can you tell me the mean lifetime?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the decay constant is not given" + }, + { + "q": "Do you know the mean lifetime 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 mean lifetime 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 mean lifetime given decay constant = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative decay constant: no example had one" + }, + { + "q": "What is a typical mean lifetime?", + "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-mean-lifetime-2/program.py b/root/organs10/physics/specialists/solved-mean-lifetime-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a40d3e169e348655edec3feca69952a8d785e4af --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime-2/program.py @@ -0,0 +1,7 @@ +"""mean lifetime from decay constant (mean lifetime (Wikidata Q1758559)) +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(decay_constant): + return 1.0/decay_constant diff --git a/root/organs10/physics/specialists/solved-mean-lifetime-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mean-lifetime-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime-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-mean-lifetime/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mean-lifetime/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime/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-mean-lifetime/panel.json b/root/organs10/physics/specialists/solved-mean-lifetime/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0a1e9903ec18b0852e7e199f4cbf7efc32a6532b --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mean lifetime for diffusion length 107.961 and mass diffusivity 59.4105?", + "a": "196.18594931702103", + "valid": true, + "kind": "compute", + "expect": 196.18594931702103, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [107.960666, 59.4105] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 107.961 and mass diffusivity of 59.4105.", + "a": "196.18594931702103", + "valid": true, + "kind": "compute", + "expect": 196.18594931702103, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [107.960666, 59.4105] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 169.527 and mass diffusivity 280.774?", + "a": "102.35783883502701", + "valid": true, + "kind": "compute", + "expect": 102.35783883502701, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [169.526958, 280.773702] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 169.527 and mass diffusivity of 280.774.", + "a": "102.35783883502701", + "valid": true, + "kind": "compute", + "expect": 102.35783883502701, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [169.526958, 280.773702] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 1.91195 and mass diffusivity 82.2401?", + "a": "0.044449858348614764", + "valid": true, + "kind": "compute", + "expect": 0.044449858348614764, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.911952, 82.240072] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 1.91195 and mass diffusivity of 82.2401.", + "a": "0.044449858348614764", + "valid": true, + "kind": "compute", + "expect": 0.044449858348614764, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.911952, 82.240072] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 1.64379 and mass diffusivity 252.709?", + "a": "0.010692390732604619", + "valid": true, + "kind": "compute", + "expect": 0.010692390732604619, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.643795, 252.709024] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 1.64379 and mass diffusivity of 252.709.", + "a": "0.010692390732604619", + "valid": true, + "kind": "compute", + "expect": 0.010692390732604619, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [1.643795, 252.709024] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 18.3169 and mass diffusivity 6.8386?", + "a": "49.060876880987344", + "valid": true, + "kind": "compute", + "expect": 49.060876880987344, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [18.316867, 6.838598] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 18.3169 and mass diffusivity of 6.8386.", + "a": "49.060876880987344", + "valid": true, + "kind": "compute", + "expect": 49.060876880987344, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [18.316867, 6.838598] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 156.502 and mass diffusivity 185.886?", + "a": "131.76237328638837", + "valid": true, + "kind": "compute", + "expect": 131.76237328638837, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [156.50181, 185.886273] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 156.502 and mass diffusivity of 185.886.", + "a": "131.76237328638837", + "valid": true, + "kind": "compute", + "expect": 131.76237328638837, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [156.50181, 185.886273] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "What is the mean lifetime for diffusion length 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Tell me the mean lifetime with diffusion length of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "What is the mean lifetime 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 mean lifetime 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 mean lifetime with diffusion length of -1.91195 and mass diffusivity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative diffusion length: no example had one" + }, + { + "q": "Which mean lifetime 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 diffusion length is 8.50728 and the mass diffusivity is 17.7888, what is the mean lifetime?", + "a": "4.068512049389283", + "valid": true, + "kind": "compute", + "expect": 4.068512049389283, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [8.507283, 17.788778] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Could you work out the mean lifetime given diffusion length = 8.50728, mass diffusivity = 17.7888?", + "a": "4.068512049389283", + "valid": true, + "kind": "compute", + "expect": 4.068512049389283, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [8.507283, 17.788778] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "I need the mean lifetime for a diffusion length of 8.24951 and a mass diffusivity of 0.634021, please.", + "a": "107.33779475702875", + "valid": true, + "kind": "compute", + "expect": 107.33779475702875, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [8.24951, 0.634021] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "If the diffusion length is 8.24951 and the mass diffusivity is 0.634021, what is the mean lifetime?", + "a": "107.33779475702875", + "valid": true, + "kind": "compute", + "expect": 107.33779475702875, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [8.24951, 0.634021] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Could you work out the mean lifetime given diffusion length = 0.318734, mass diffusivity = 9.56607?", + "a": "0.010619970649664055", + "valid": true, + "kind": "compute", + "expect": 0.010619970649664055, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.318734, 9.566071] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "I need the mean lifetime for a diffusion length of 0.318734 and a mass diffusivity of 9.56607, please.", + "a": "0.010619970649664055", + "valid": true, + "kind": "compute", + "expect": 0.010619970649664055, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.318734, 9.566071] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "If the diffusion length is 0.671697 and the mass diffusivity is 14.2496, what is the mean lifetime?", + "a": "0.031662509806997814", + "valid": true, + "kind": "compute", + "expect": 0.031662509806997814, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.671697, 14.249569] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Could you work out the mean lifetime given diffusion length = 0.671697, mass diffusivity = 14.2496?", + "a": "0.031662509806997814", + "valid": true, + "kind": "compute", + "expect": 0.031662509806997814, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [0.671697, 14.249569] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "I need the mean lifetime for a diffusion length of 21.7931 and a mass diffusivity of 29.5106, please.", + "a": "16.093885686410946", + "valid": true, + "kind": "compute", + "expect": 16.093885686410946, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [21.793126, 29.510609] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "If the diffusion length is 21.7931 and the mass diffusivity is 29.5106, what is the mean lifetime?", + "a": "16.093885686410946", + "valid": true, + "kind": "compute", + "expect": 16.093885686410946, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [21.793126, 29.510609] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "Could you work out the mean lifetime given diffusion length = 153.15, mass diffusivity = 18.5953?", + "a": "1261.3344397561323", + "valid": true, + "kind": "compute", + "expect": 1261.3344397561323, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [153.149965, 18.595315] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "I need the mean lifetime for a diffusion length of 153.15 and a mass diffusivity of 18.5953, please.", + "a": "1261.3344397561323", + "valid": true, + "kind": "compute", + "expect": 1261.3344397561323, + "dtype": "quantity", + "unit": "s", + "why": "mean lifetime for [153.149965, 18.595315] (the system diffusion length (Wikidata Q106097176))" + }, + { + "q": "If the diffusion length is 8.50728, what is the mean lifetime?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Could you work out the mean lifetime given diffusion length = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Do you know the mean lifetime 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 mean lifetime 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 mean lifetime given diffusion length = -0.318734, mass diffusivity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative diffusion length: no example had one" + }, + { + "q": "What is a typical mean lifetime?", + "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-mean-lifetime/program.py b/root/organs10/physics/specialists/solved-mean-lifetime/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3018d36c72403e603423f7f8b15ec2fff7679b5f --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime/program.py @@ -0,0 +1,7 @@ +"""mean lifetime from diffusion length, mass diffusivity (diffusion length (Wikidata Q106097176)) +The maths organ (systems.py): solved from the system q0 = sqrt(q1*q2); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(diffusion_length, mass_diffusivity): + return 1.0*diffusion_length**2/mass_diffusivity diff --git a/root/organs10/physics/specialists/solved-mean-lifetime/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mean-lifetime/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-lifetime/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-mean-linear-range/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mean-linear-range/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-linear-range/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-mean-linear-range/panel.json b/root/organs10/physics/specialists/solved-mean-linear-range/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5350e34d9633bb6bc8d14fe68ac34ef02eb4feea --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-linear-range/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mean linear range for mean mass range 107.961 and mass density 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [107.960666, 59.4105] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 107.961 and mass density of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [107.960666, 59.4105] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 169.527 and mass density 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [169.526958, 280.773702] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 169.527 and mass density of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [169.526958, 280.773702] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 1.91195 and mass density 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [1.911952, 82.240072] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 1.91195 and mass density of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [1.911952, 82.240072] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 1.64379 and mass density 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [1.643795, 252.709024] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 1.64379 and mass density of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [1.643795, 252.709024] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 18.3169 and mass density 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [18.316867, 6.838598] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 18.3169 and mass density of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [18.316867, 6.838598] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 156.502 and mass density 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [156.50181, 185.886273] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean linear range with mean mass range of 156.502 and mass density of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [156.50181, 185.886273] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean linear range for mean mass range 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Tell me the mean linear range with mean mass range 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 mean linear range 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 mean linear range 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 mean linear range with mean mass range of -1.91195 and mass density of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean mass range: no example had one" + }, + { + "q": "Which mean linear range 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 mass range is 8.50728 and the mass density is 17.7888, what is the mean linear range?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [8.507283, 17.788778] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean linear range given mean mass range = 8.50728, mass density = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [8.507283, 17.788778] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean linear range for a mean mass range of 8.24951 and a mass density of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [8.24951, 0.634021] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean mass range is 8.24951 and the mass density is 0.634021, what is the mean linear range?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [8.24951, 0.634021] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean linear range given mean mass range = 0.318734, mass density = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [0.318734, 9.566071] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean linear range for a mean mass range of 0.318734 and a mass density of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [0.318734, 9.566071] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean mass range is 0.671697 and the mass density is 14.2496, what is the mean linear range?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [0.671697, 14.249569] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean linear range given mean mass range = 0.671697, mass density = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [0.671697, 14.249569] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean linear range for a mean mass range of 21.7931 and a mass density of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [21.793126, 29.510609] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean mass range is 21.7931 and the mass density is 29.5106, what is the mean linear range?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [21.793126, 29.510609] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean linear range given mean mass range = 153.15, mass density = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [153.149965, 18.595315] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean linear range for a mean mass range of 153.15 and a mass density of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m", + "why": "mean linear range for [153.149965, 18.595315] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean mass range is 8.50728, what is the mean linear range?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Could you work out the mean linear range given mean mass range = 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 mean linear range 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 mean linear range 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 mean linear range given mean mass range = -0.318734, mass density = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean mass range: no example had one" + }, + { + "q": "What is a typical mean linear range?", + "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-mean-linear-range/program.py b/root/organs10/physics/specialists/solved-mean-linear-range/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d15946508e495dd29b9a1ab28d5fb0c35f7f0986 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-linear-range/program.py @@ -0,0 +1,7 @@ +"""mean linear range from mean mass range, mass density (mean mass range (Wikidata Q98681670)) +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(mean_mass_range, mass_density): + return 1.0*mean_mass_range/mass_density diff --git a/root/organs10/physics/specialists/solved-mean-linear-range/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mean-linear-range/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-linear-range/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-mean-mass-range/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mean-mass-range/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-mass-range/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-mean-mass-range/panel.json b/root/organs10/physics/specialists/solved-mean-mass-range/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d00f7dceb3705319eb60b5f75744db12bb7295a8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-mass-range/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mean mass range for mean linear range 107.961 and mass density 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [107.960666, 59.4105] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 107.961 and mass density of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [107.960666, 59.4105] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 169.527 and mass density 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [169.526958, 280.773702] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 169.527 and mass density of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [169.526958, 280.773702] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 1.91195 and mass density 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [1.911952, 82.240072] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 1.91195 and mass density of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [1.911952, 82.240072] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 1.64379 and mass density 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [1.643795, 252.709024] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 1.64379 and mass density of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [1.643795, 252.709024] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 18.3169 and mass density 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [18.316867, 6.838598] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 18.3169 and mass density of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [18.316867, 6.838598] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 156.502 and mass density 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [156.50181, 185.886273] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Tell me the mean mass range with mean linear range of 156.502 and mass density of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [156.50181, 185.886273] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "What is the mean mass range for mean linear range 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Tell me the mean mass range with mean linear range 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 mean mass range 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 mean mass range 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 mean mass range with mean linear range of -1.91195 and mass density of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean linear range: no example had one" + }, + { + "q": "Which mean mass range 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 linear range is 8.50728 and the mass density is 17.7888, what is the mean mass range?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [8.507283, 17.788778] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean mass range given mean linear range = 8.50728, mass density = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [8.507283, 17.788778] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean mass range for a mean linear range of 8.24951 and a mass density of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [8.24951, 0.634021] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean linear range is 8.24951 and the mass density is 0.634021, what is the mean mass range?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [8.24951, 0.634021] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean mass range given mean linear range = 0.318734, mass density = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [0.318734, 9.566071] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean mass range for a mean linear range of 0.318734 and a mass density of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [0.318734, 9.566071] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean linear range is 0.671697 and the mass density is 14.2496, what is the mean mass range?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [0.671697, 14.249569] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean mass range given mean linear range = 0.671697, mass density = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [0.671697, 14.249569] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean mass range for a mean linear range of 21.7931 and a mass density of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [21.793126, 29.510609] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean linear range is 21.7931 and the mass density is 29.5106, what is the mean mass range?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [21.793126, 29.510609] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "Could you work out the mean mass range given mean linear range = 153.15, mass density = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [153.149965, 18.595315] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "I need the mean mass range for a mean linear range of 153.15 and a mass density of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg/m^2", + "why": "mean mass range for [153.149965, 18.595315] (the system mean mass range (Wikidata Q98681670))" + }, + { + "q": "If the mean linear range is 8.50728, what is the mean mass range?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass density is not given" + }, + { + "q": "Could you work out the mean mass range given mean linear range = 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 mean mass range 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 mean mass range 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 mean mass range given mean linear range = -0.318734, mass density = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mean linear range: no example had one" + }, + { + "q": "What is a typical mean mass range?", + "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-mean-mass-range/program.py b/root/organs10/physics/specialists/solved-mean-mass-range/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ea56664934f8088551e11ed2b00d9a58858d2272 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-mass-range/program.py @@ -0,0 +1,7 @@ +"""mean mass range from mean linear range, mass density (mean mass range (Wikidata Q98681670)) +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(mean_linear_range, mass_density): + return 1.0*mass_density*mean_linear_range diff --git a/root/organs10/physics/specialists/solved-mean-mass-range/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mean-mass-range/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mean-mass-range/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-mechanical-efficiency/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-efficiency/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-mechanical-efficiency/panel.json b/root/organs10/physics/specialists/solved-mechanical-efficiency/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7bd0f947a0f99aaa3d407cb051a116f56fe80c6a --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-efficiency/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical efficiency for mechanical output power 107.961 and mechanical input power 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 107.961 and mechanical input power of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 169.527 and mechanical input power 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 169.527 and mechanical input power of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 1.91195 and mechanical input power 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 1.91195 and mechanical input power of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 1.64379 and mechanical input power 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 1.64379 and mechanical input power of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 18.3169 and mechanical input power 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 18.3169 and mechanical input power of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 156.502 and mechanical input power 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 156.502 and mechanical input power of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical efficiency for mechanical output power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical input power is not given" + }, + { + "q": "Tell me the mechanical efficiency with mechanical output power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical input power is not given" + }, + { + "q": "What is the mechanical 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 mechanical 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 mechanical efficiency with mechanical output power of -1.91195 and mechanical input power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical output power: no example had one" + }, + { + "q": "Which mechanical 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 mechanical output power is 8.50728 and the mechanical input power is 17.7888, what is the mechanical efficiency?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical efficiency given mechanical output power = 8.50728, mechanical input power = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical efficiency for a mechanical output power of 8.24951 and a mechanical input power of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 8.24951 and the mechanical input power is 0.634021, what is the mechanical efficiency?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical efficiency given mechanical output power = 0.318734, mechanical input power = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical efficiency for a mechanical output power of 0.318734 and a mechanical input power of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 0.671697 and the mechanical input power is 14.2496, what is the mechanical efficiency?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical efficiency given mechanical output power = 0.671697, mechanical input power = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical efficiency for a mechanical output power of 21.7931 and a mechanical input power of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 21.7931 and the mechanical input power is 29.5106, what is the mechanical efficiency?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical efficiency given mechanical output power = 153.15, mechanical input power = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical efficiency for a mechanical output power of 153.15 and a mechanical input power of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "mechanical efficiency for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 8.50728, what is the mechanical efficiency?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical input power is not given" + }, + { + "q": "Could you work out the mechanical efficiency given mechanical output power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical input power is not given" + }, + { + "q": "Do you know the mechanical 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 mechanical 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 mechanical efficiency given mechanical output power = -0.318734, mechanical input power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical output power: no example had one" + }, + { + "q": "What is a typical mechanical 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-mechanical-efficiency/program.py b/root/organs10/physics/specialists/solved-mechanical-efficiency/program.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b082103e5bc3268062f5e9e7d720cb27856dfe --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-efficiency/program.py @@ -0,0 +1,7 @@ +"""mechanical efficiency from mechanical output power, mechanical input power (mechanical efficiency (Wikidata Q2628085)) +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(mechanical_output_power, mechanical_input_power): + return 1.0*mechanical_output_power/mechanical_input_power diff --git a/root/organs10/physics/specialists/solved-mechanical-efficiency/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-efficiency/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-mechanical-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-mechanical-energy/panel.json b/root/organs10/physics/specialists/solved-mechanical-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e415c95032381fb8b43a884e6ea73bf8e9901a1b --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical energy for kinetic energy 107.961 and potential energy 59.4105?", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [107.960666, 59.4105] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 107.961 and potential energy of 59.4105.", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [107.960666, 59.4105] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 169.527 and potential energy 280.774?", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [169.526958, 280.773702] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 169.527 and potential energy of 280.774.", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [169.526958, 280.773702] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 1.91195 and potential energy 82.2401?", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [1.911952, 82.240072] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 1.91195 and potential energy of 82.2401.", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [1.911952, 82.240072] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 1.64379 and potential energy 252.709?", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [1.643795, 252.709024] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 1.64379 and potential energy of 252.709.", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [1.643795, 252.709024] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 18.3169 and potential energy 6.8386?", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [18.316867, 6.838598] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 18.3169 and potential energy of 6.8386.", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [18.316867, 6.838598] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 156.502 and potential energy 185.886?", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [156.50181, 185.886273] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 156.502 and potential energy of 185.886.", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [156.50181, 185.886273] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "What is the mechanical energy for kinetic energy 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the potential energy is not given" + }, + { + "q": "Tell me the mechanical energy with kinetic energy of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the potential energy is not given" + }, + { + "q": "What is the mechanical 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 mechanical 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 mechanical energy with kinetic energy of -1.91195 and potential energy of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative kinetic energy: no example had one" + }, + { + "q": "Which mechanical 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 kinetic energy is 8.50728 and the potential energy is 17.7888, what is the mechanical energy?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [8.507283, 17.788778] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the mechanical energy given kinetic energy = 8.50728, potential energy = 17.7888?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [8.507283, 17.788778] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the mechanical energy for a kinetic energy of 8.24951 and a potential energy of 0.634021, please.", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [8.24951, 0.634021] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the kinetic energy is 8.24951 and the potential energy is 0.634021, what is the mechanical energy?", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [8.24951, 0.634021] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the mechanical energy given kinetic energy = 0.318734, potential energy = 9.56607?", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [0.318734, 9.566071] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the mechanical energy for a kinetic energy of 0.318734 and a potential energy of 9.56607, please.", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [0.318734, 9.566071] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the kinetic energy is 0.671697 and the potential energy is 14.2496, what is the mechanical energy?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [0.671697, 14.249569] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the mechanical energy given kinetic energy = 0.671697, potential energy = 14.2496?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [0.671697, 14.249569] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the mechanical energy for a kinetic energy of 21.7931 and a potential energy of 29.5106, please.", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [21.793126, 29.510609] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the kinetic energy is 21.7931 and the potential energy is 29.5106, what is the mechanical energy?", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [21.793126, 29.510609] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "Could you work out the mechanical energy given kinetic energy = 153.15, potential energy = 18.5953?", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [153.149965, 18.595315] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "I need the mechanical energy for a kinetic energy of 153.15 and a potential energy of 18.5953, please.", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "J", + "why": "mechanical energy for [153.149965, 18.595315] (the system mechanical energy (Wikidata Q184550))" + }, + { + "q": "If the kinetic energy is 8.50728, what is the mechanical energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the potential energy is not given" + }, + { + "q": "Could you work out the mechanical energy given kinetic energy = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the potential energy is not given" + }, + { + "q": "Do you know the mechanical 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 mechanical 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 mechanical energy given kinetic energy = -0.318734, potential energy = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative kinetic energy: no example had one" + }, + { + "q": "What is a typical mechanical 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-mechanical-energy/program.py b/root/organs10/physics/specialists/solved-mechanical-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d8907b032b6bf91144f4c39b8ba8ea52c26e0556 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-energy/program.py @@ -0,0 +1,7 @@ +"""mechanical energy from kinetic energy, potential 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(kinetic_energy, potential_energy): + return 1.0*kinetic_energy + 1.0*potential_energy diff --git a/root/organs10/physics/specialists/solved-mechanical-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-mechanical-impedance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-impedance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-impedance/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-mechanical-impedance/panel.json b/root/organs10/physics/specialists/solved-mechanical-impedance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..959ffc5ac39f504947baad94e8fb4580542cb569 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-impedance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical impedance for acoustic impedance 107.961 and area 59.4105?", + "a": "381058.77958914574", + "valid": true, + "kind": "compute", + "expect": 381058.77958914574, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [107.960666, 59.4105] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 107.961 and area of 59.4105.", + "a": "381058.77958914574", + "valid": true, + "kind": "compute", + "expect": 381058.77958914574, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [107.960666, 59.4105] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 169.527 and area 280.774?", + "a": "13364466.42057454", + "valid": true, + "kind": "compute", + "expect": 13364466.42057454, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [169.526958, 280.773702] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 169.527 and area of 280.774.", + "a": "13364466.42057454", + "valid": true, + "kind": "compute", + "expect": 13364466.42057454, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [169.526958, 280.773702] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 1.91195 and area 82.2401?", + "a": "12931.350797066336", + "valid": true, + "kind": "compute", + "expect": 12931.350797066336, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [1.911952, 82.240072] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 1.91195 and area of 82.2401.", + "a": "12931.350797066336", + "valid": true, + "kind": "compute", + "expect": 12931.350797066336, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [1.911952, 82.240072] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 1.64379 and area 252.709?", + "a": "104975.82286408338", + "valid": true, + "kind": "compute", + "expect": 104975.82286408338, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [1.643795, 252.709024] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 1.64379 and area of 252.709.", + "a": "104975.82286408338", + "valid": true, + "kind": "compute", + "expect": 104975.82286408338, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [1.643795, 252.709024] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 18.3169 and area 6.8386?", + "a": "856.6143593859481", + "valid": true, + "kind": "compute", + "expect": 856.6143593859481, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [18.316867, 6.838598] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 18.3169 and area of 6.8386.", + "a": "856.6143593859481", + "valid": true, + "kind": "compute", + "expect": 856.6143593859481, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [18.316867, 6.838598] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 156.502 and area 185.886?", + "a": "5407717.588152708", + "valid": true, + "kind": "compute", + "expect": 5407717.588152708, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [156.50181, 185.886273] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 156.502 and area of 185.886.", + "a": "5407717.588152708", + "valid": true, + "kind": "compute", + "expect": 5407717.588152708, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [156.50181, 185.886273] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "What is the mechanical impedance for acoustic impedance 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the mechanical impedance with acoustic impedance of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the mechanical impedance 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 mechanical impedance 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 mechanical impedance with acoustic impedance of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative acoustic impedance: no example had one" + }, + { + "q": "Which mechanical impedance 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 acoustic impedance is 8.50728 and the area is 17.7888, what is the mechanical impedance?", + "a": "2692.0498594103697", + "valid": true, + "kind": "compute", + "expect": 2692.0498594103697, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [8.507283, 17.788778] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Could you work out the mechanical impedance given acoustic impedance = 8.50728, area = 17.7888?", + "a": "2692.0498594103697", + "valid": true, + "kind": "compute", + "expect": 2692.0498594103697, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [8.507283, 17.788778] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "I need the mechanical impedance for an acoustic impedance of 8.24951 and an area of 0.634021, please.", + "a": "3.3161593761140393", + "valid": true, + "kind": "compute", + "expect": 3.3161593761140393, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [8.24951, 0.634021] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "If the acoustic impedance is 8.24951 and the area is 0.634021, what is the mechanical impedance?", + "a": "3.3161593761140393", + "valid": true, + "kind": "compute", + "expect": 3.3161593761140393, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [8.24951, 0.634021] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Could you work out the mechanical impedance given acoustic impedance = 0.318734, area = 9.56607?", + "a": "29.16726159383275", + "valid": true, + "kind": "compute", + "expect": 29.16726159383275, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [0.318734, 9.566071] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "I need the mechanical impedance for an acoustic impedance of 0.318734 and an area of 9.56607, please.", + "a": "29.16726159383275", + "valid": true, + "kind": "compute", + "expect": 29.16726159383275, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [0.318734, 9.566071] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "If the acoustic impedance is 0.671697 and the area is 14.2496, what is the mechanical impedance?", + "a": "136.38826801335216", + "valid": true, + "kind": "compute", + "expect": 136.38826801335216, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [0.671697, 14.249569] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Could you work out the mechanical impedance given acoustic impedance = 0.671697, area = 14.2496?", + "a": "136.38826801335216", + "valid": true, + "kind": "compute", + "expect": 136.38826801335216, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [0.671697, 14.249569] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "I need the mechanical impedance for an acoustic impedance of 21.7931 and an area of 29.5106, please.", + "a": "18979.11133874426", + "valid": true, + "kind": "compute", + "expect": 18979.11133874426, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [21.793126, 29.510609] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "If the acoustic impedance is 21.7931 and the area is 29.5106, what is the mechanical impedance?", + "a": "18979.11133874426", + "valid": true, + "kind": "compute", + "expect": 18979.11133874426, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [21.793126, 29.510609] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "Could you work out the mechanical impedance given acoustic impedance = 153.15, area = 18.5953?", + "a": "52957.07669974909", + "valid": true, + "kind": "compute", + "expect": 52957.07669974909, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [153.149965, 18.595315] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "I need the mechanical impedance for an acoustic impedance of 153.15 and an area of 18.5953, please.", + "a": "52957.07669974909", + "valid": true, + "kind": "compute", + "expect": 52957.07669974909, + "dtype": "quantity", + "unit": "kg/s", + "why": "mechanical impedance for [153.149965, 18.595315] (the system mechanical impedance (Wikidata Q6421317))" + }, + { + "q": "If the acoustic impedance is 8.50728, what is the mechanical impedance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the mechanical impedance given acoustic impedance = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the mechanical impedance 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 mechanical impedance 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 mechanical impedance given acoustic impedance = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative acoustic impedance: no example had one" + }, + { + "q": "What is a typical mechanical impedance?", + "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-mechanical-impedance/program.py b/root/organs10/physics/specialists/solved-mechanical-impedance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4c61a82a0ec6b35eaa1a3cc50a84cb230e4ff991 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-impedance/program.py @@ -0,0 +1,7 @@ +"""mechanical impedance from acoustic impedance, area (mechanical impedance (Wikidata Q6421317)) +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(acoustic_impedance, area): + return 1.0*acoustic_impedance*area**2 diff --git a/root/organs10/physics/specialists/solved-mechanical-impedance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-impedance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-impedance/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-mechanical-input-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-input-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-input-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-mechanical-input-power/panel.json b/root/organs10/physics/specialists/solved-mechanical-input-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b5688ea701ef0cc2a1199afcadee12f590de0352 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-input-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical input power for mechanical output power 107.961 and mechanical efficiency 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 107.961 and mechanical efficiency of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 169.527 and mechanical efficiency 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 169.527 and mechanical efficiency of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 1.91195 and mechanical efficiency 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 1.91195 and mechanical efficiency of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 1.64379 and mechanical efficiency 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 1.64379 and mechanical efficiency of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 18.3169 and mechanical efficiency 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 18.3169 and mechanical efficiency of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 156.502 and mechanical efficiency 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 156.502 and mechanical efficiency of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical input power for mechanical output power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Tell me the mechanical input power with mechanical output power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "What is the mechanical input 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 mechanical input 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 mechanical input power with mechanical output power of -1.91195 and mechanical efficiency of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical output power: no example had one" + }, + { + "q": "Which mechanical input 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 mechanical output power is 8.50728 and the mechanical efficiency is 17.7888, what is the mechanical input power?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical input power given mechanical output power = 8.50728, mechanical efficiency = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical input power for a mechanical output power of 8.24951 and a mechanical efficiency of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 8.24951 and the mechanical efficiency is 0.634021, what is the mechanical input power?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical input power given mechanical output power = 0.318734, mechanical efficiency = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical input power for a mechanical output power of 0.318734 and a mechanical efficiency of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 0.671697 and the mechanical efficiency is 14.2496, what is the mechanical input power?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical input power given mechanical output power = 0.671697, mechanical efficiency = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical input power for a mechanical output power of 21.7931 and a mechanical efficiency of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 21.7931 and the mechanical efficiency is 29.5106, what is the mechanical input power?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical input power given mechanical output power = 153.15, mechanical efficiency = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical input power for a mechanical output power of 153.15 and a mechanical efficiency of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "W", + "why": "mechanical input power for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical output power is 8.50728, what is the mechanical input power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Could you work out the mechanical input power given mechanical output power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Do you know the mechanical input 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 mechanical input 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 mechanical input power given mechanical output power = -0.318734, mechanical efficiency = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical output power: no example had one" + }, + { + "q": "What is a typical mechanical input 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-mechanical-input-power/program.py b/root/organs10/physics/specialists/solved-mechanical-input-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..148f0a64496ee54a154d67fd8c75e9938ef725b5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-input-power/program.py @@ -0,0 +1,7 @@ +"""mechanical input power from mechanical output power, mechanical efficiency (mechanical efficiency (Wikidata Q2628085)) +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(mechanical_output_power, mechanical_efficiency): + return 1.0*mechanical_output_power/mechanical_efficiency diff --git a/root/organs10/physics/specialists/solved-mechanical-input-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-input-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-input-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-mechanical-output-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-output-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-output-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-mechanical-output-power/panel.json b/root/organs10/physics/specialists/solved-mechanical-output-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..28cb7e03ca8115371892f63c0338023c1fa53aac --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-output-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical output power for mechanical input power 107.961 and mechanical efficiency 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 107.961 and mechanical efficiency of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [107.960666, 59.4105] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 169.527 and mechanical efficiency 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 169.527 and mechanical efficiency of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [169.526958, 280.773702] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 1.91195 and mechanical efficiency 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 1.91195 and mechanical efficiency of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [1.911952, 82.240072] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 1.64379 and mechanical efficiency 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 1.64379 and mechanical efficiency of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [1.643795, 252.709024] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 18.3169 and mechanical efficiency 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 18.3169 and mechanical efficiency of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [18.316867, 6.838598] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 156.502 and mechanical efficiency 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 156.502 and mechanical efficiency of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [156.50181, 185.886273] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "What is the mechanical output power for mechanical input power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Tell me the mechanical output power with mechanical input power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "What is the mechanical output 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 mechanical output 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 mechanical output power with mechanical input power of -1.91195 and mechanical efficiency of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical input power: no example had one" + }, + { + "q": "Which mechanical output 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 mechanical input power is 8.50728 and the mechanical efficiency is 17.7888, what is the mechanical output power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical output power given mechanical input power = 8.50728, mechanical efficiency = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [8.507283, 17.788778] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical output power for a mechanical input power of 8.24951 and a mechanical efficiency of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical input power is 8.24951 and the mechanical efficiency is 0.634021, what is the mechanical output power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [8.24951, 0.634021] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical output power given mechanical input power = 0.318734, mechanical efficiency = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical output power for a mechanical input power of 0.318734 and a mechanical efficiency of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [0.318734, 9.566071] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical input power is 0.671697 and the mechanical efficiency is 14.2496, what is the mechanical output power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical output power given mechanical input power = 0.671697, mechanical efficiency = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [0.671697, 14.249569] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical output power for a mechanical input power of 21.7931 and a mechanical efficiency of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical input power is 21.7931 and the mechanical efficiency is 29.5106, what is the mechanical output power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [21.793126, 29.510609] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "Could you work out the mechanical output power given mechanical input power = 153.15, mechanical efficiency = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "I need the mechanical output power for a mechanical input power of 153.15 and a mechanical efficiency of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "mechanical output power for [153.149965, 18.595315] (the system mechanical efficiency (Wikidata Q2628085))" + }, + { + "q": "If the mechanical input power is 8.50728, what is the mechanical output power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Could you work out the mechanical output power given mechanical input power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mechanical efficiency is not given" + }, + { + "q": "Do you know the mechanical output 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 mechanical output 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 mechanical output power given mechanical input power = -0.318734, mechanical efficiency = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mechanical input power: no example had one" + }, + { + "q": "What is a typical mechanical output 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-mechanical-output-power/program.py b/root/organs10/physics/specialists/solved-mechanical-output-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6efa25c102e0c7955cbe1432aaf0e9a70e5ec6 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-output-power/program.py @@ -0,0 +1,7 @@ +"""mechanical output power from mechanical input power, mechanical efficiency (mechanical efficiency (Wikidata Q2628085)) +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(mechanical_input_power, mechanical_efficiency): + return 1.0*mechanical_efficiency*mechanical_input_power diff --git a/root/organs10/physics/specialists/solved-mechanical-output-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-output-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-output-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-mechanical-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mechanical-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-mechanical-power/panel.json b/root/organs10/physics/specialists/solved-mechanical-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f1147797df823465da6102f9e4101d0c9fb7e7d7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mechanical power for force 107.961 and velocity 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [107.960666, 59.4105] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 107.961 and velocity of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [107.960666, 59.4105] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 169.527 and velocity 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [169.526958, 280.773702] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 169.527 and velocity of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [169.526958, 280.773702] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 1.91195 and velocity 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [1.911952, 82.240072] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 1.91195 and velocity of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [1.911952, 82.240072] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 1.64379 and velocity 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [1.643795, 252.709024] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 1.64379 and velocity of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [1.643795, 252.709024] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 18.3169 and velocity 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [18.316867, 6.838598] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 18.3169 and velocity of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [18.316867, 6.838598] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 156.502 and velocity 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [156.50181, 185.886273] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Tell me the mechanical power with force of 156.502 and velocity of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [156.50181, 185.886273] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "What is the mechanical power for force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the velocity is not given" + }, + { + "q": "Tell me the mechanical power with force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the velocity is not given" + }, + { + "q": "What is the mechanical 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 mechanical 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 mechanical power with force of -1.91195 and velocity 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 mechanical 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 force is 8.50728 and the velocity is 17.7888, what is the mechanical power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [8.507283, 17.788778] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Could you work out the mechanical power given force = 8.50728, velocity = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [8.507283, 17.788778] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "I need the mechanical power for a force of 8.24951 and a velocity of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [8.24951, 0.634021] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "If the force is 8.24951 and the velocity is 0.634021, what is the mechanical power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [8.24951, 0.634021] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Could you work out the mechanical power given force = 0.318734, velocity = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [0.318734, 9.566071] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "I need the mechanical power for a force of 0.318734 and a velocity of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [0.318734, 9.566071] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "If the force is 0.671697 and the velocity is 14.2496, what is the mechanical power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [0.671697, 14.249569] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Could you work out the mechanical power given force = 0.671697, velocity = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [0.671697, 14.249569] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "I need the mechanical power for a force of 21.7931 and a velocity of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [21.793126, 29.510609] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "If the force is 21.7931 and the velocity is 29.5106, what is the mechanical power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [21.793126, 29.510609] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "Could you work out the mechanical power given force = 153.15, velocity = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [153.149965, 18.595315] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "I need the mechanical power for a force of 153.15 and a velocity of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "mechanical power for [153.149965, 18.595315] (the system mechanical power (Wikidata Q80806956))" + }, + { + "q": "If the force is 8.50728, what is the mechanical power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the velocity is not given" + }, + { + "q": "Could you work out the mechanical power given force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the velocity is not given" + }, + { + "q": "Do you know the mechanical 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 mechanical 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 mechanical power given force = -0.318734, velocity = 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 mechanical 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-mechanical-power/program.py b/root/organs10/physics/specialists/solved-mechanical-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..48108cf20941b0c122f7c1089c679878e57ca164 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-power/program.py @@ -0,0 +1,7 @@ +"""mechanical power from force, velocity (mechanical power (Wikidata Q80806956)) +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(force, velocity): + return 1.0*force*velocity diff --git a/root/organs10/physics/specialists/solved-mechanical-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mechanical-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mechanical-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-migration-area-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-migration-area-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area-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-migration-area-2/panel.json b/root/organs10/physics/specialists/solved-migration-area-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0ab42eb7a73e46d09820856c55c6c9f0b04ec7ed --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the migration area for migration length 107.961?", + "a": "11655.505379404009", + "valid": true, + "kind": "compute", + "expect": 11655.505379404009, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [107.960666] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 107.961.", + "a": "11655.505379404009", + "valid": true, + "kind": "compute", + "expect": 11655.505379404009, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [107.960666] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area for migration length 22.652?", + "a": "513.1141367892745", + "valid": true, + "kind": "compute", + "expect": 513.1141367892745, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [22.652023] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 22.652.", + "a": "513.1141367892745", + "valid": true, + "kind": "compute", + "expect": 513.1141367892745, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [22.652023] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area for migration length 173.394?", + "a": "30065.353839428797", + "valid": true, + "kind": "compute", + "expect": 30065.353839428797, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [173.393638] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 173.394.", + "a": "30065.353839428797", + "valid": true, + "kind": "compute", + "expect": 30065.353839428797, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [173.393638] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area for migration length 126.709?", + "a": "16055.23449176202", + "valid": true, + "kind": "compute", + "expect": 16055.23449176202, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [126.709252] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 126.709.", + "a": "16055.23449176202", + "valid": true, + "kind": "compute", + "expect": 16055.23449176202, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [126.709252] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area for migration length 0.671697?", + "a": "0.4511771282113607", + "valid": true, + "kind": "compute", + "expect": 0.4511771282113607, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.671697] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 0.671697.", + "a": "0.4511771282113607", + "valid": true, + "kind": "compute", + "expect": 0.4511771282113607, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.671697] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area for migration length 1.16997?", + "a": "1.3688251350119873", + "valid": true, + "kind": "compute", + "expect": 1.3688251350119873, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.169968] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration area with migration length of 1.16997.", + "a": "1.3688251350119873", + "valid": true, + "kind": "compute", + "expect": 1.3688251350119873, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.169968] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration area?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration length is not given" + }, + { + "q": "Could you work out the migration area, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration length is not given" + }, + { + "q": "What is the migration area 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 migration area 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 migration area with migration length of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative migration length: no example had one" + }, + { + "q": "Which migration area 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 migration length is 2.57003, what is the migration area?", + "a": "6.605053755275534", + "valid": true, + "kind": "compute", + "expect": 6.605053755275534, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [2.57003] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration area given migration length = 2.57003?", + "a": "6.605053755275534", + "valid": true, + "kind": "compute", + "expect": 6.605053755275534, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [2.57003] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration area for a migration length of 48.921, please.", + "a": "2393.2633467253613", + "valid": true, + "kind": "compute", + "expect": 2393.2633467253613, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [48.920991] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration length is 48.921, what is the migration area?", + "a": "2393.2633467253613", + "valid": true, + "kind": "compute", + "expect": 2393.2633467253613, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [48.920991] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration area given migration length = 0.348438?", + "a": "0.12140880961720626", + "valid": true, + "kind": "compute", + "expect": 0.12140880961720626, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.348438] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration area for a migration length of 0.348438, please.", + "a": "0.12140880961720626", + "valid": true, + "kind": "compute", + "expect": 0.12140880961720626, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.348438] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration length is 252.709, what is the migration area?", + "a": "63861.85093714829", + "valid": true, + "kind": "compute", + "expect": 63861.85093714829, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [252.709024] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration area given migration length = 252.709?", + "a": "63861.85093714829", + "valid": true, + "kind": "compute", + "expect": 63861.85093714829, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [252.709024] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration area for a migration length of 20.3966, please.", + "a": "416.01957669573414", + "valid": true, + "kind": "compute", + "expect": 416.01957669573414, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [20.396558] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration length is 20.3966, what is the migration area?", + "a": "416.01957669573414", + "valid": true, + "kind": "compute", + "expect": 416.01957669573414, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [20.396558] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration area given migration length = 134.993?", + "a": "18223.098596394928", + "valid": true, + "kind": "compute", + "expect": 18223.098596394928, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [134.992958] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration area for a migration length of 134.993, please.", + "a": "18223.098596394928", + "valid": true, + "kind": "compute", + "expect": 18223.098596394928, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [134.992958] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration area, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration length is not given" + }, + { + "q": "Can you tell me the migration area?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration length is not given" + }, + { + "q": "Do you know the migration area 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 migration area 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 migration area given migration length = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative migration length: no example had one" + }, + { + "q": "What is a typical migration area?", + "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-migration-area-2/program.py b/root/organs10/physics/specialists/solved-migration-area-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..afa775870d5fa041c54237fb75fb426be5cc24cf --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area-2/program.py @@ -0,0 +1,7 @@ +"""migration area from migration length (migration length (Wikidata Q98998318)) +The maths organ (systems.py): solved from the system q1 = sqrt(q0); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(migration_length): + return 1.0*migration_length**2 diff --git a/root/organs10/physics/specialists/solved-migration-area-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-migration-area-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area-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-migration-area/organ_formula_v2.py b/root/organs10/physics/specialists/solved-migration-area/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area/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-migration-area/panel.json b/root/organs10/physics/specialists/solved-migration-area/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..456892a3b640132604aeace9370f6336e204d0c2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the migration area for slowing-down area 107.961 and diffusion area 59.4105?", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [107.960666, 59.4105] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 107.961 and diffusion area of 59.4105.", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [107.960666, 59.4105] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 169.527 and diffusion area 280.774?", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [169.526958, 280.773702] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 169.527 and diffusion area of 280.774.", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [169.526958, 280.773702] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 1.91195 and diffusion area 82.2401?", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.911952, 82.240072] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 1.91195 and diffusion area of 82.2401.", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.911952, 82.240072] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 1.64379 and diffusion area 252.709?", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.643795, 252.709024] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 1.64379 and diffusion area of 252.709.", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [1.643795, 252.709024] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 18.3169 and diffusion area 6.8386?", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [18.316867, 6.838598] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 18.3169 and diffusion area of 6.8386.", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [18.316867, 6.838598] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 156.502 and diffusion area 185.886?", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [156.50181, 185.886273] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Tell me the migration area with slowing-down area of 156.502 and diffusion area of 185.886.", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [156.50181, 185.886273] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "What is the migration area for slowing-down area 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diffusion area is not given" + }, + { + "q": "Tell me the migration area with slowing-down area of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diffusion area is not given" + }, + { + "q": "What is the migration area 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 migration area 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 migration area with slowing-down area of -1.91195 and diffusion area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative slowing-down area: no example had one" + }, + { + "q": "Which migration area 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 slowing-down area is 8.50728 and the diffusion area is 17.7888, what is the migration area?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [8.507283, 17.788778] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Could you work out the migration area given slowing-down area = 8.50728, diffusion area = 17.7888?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [8.507283, 17.788778] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "I need the migration area for a slowing-down area of 8.24951 and a diffusion area of 0.634021, please.", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [8.24951, 0.634021] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "If the slowing-down area is 8.24951 and the diffusion area is 0.634021, what is the migration area?", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [8.24951, 0.634021] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Could you work out the migration area given slowing-down area = 0.318734, diffusion area = 9.56607?", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.318734, 9.566071] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "I need the migration area for a slowing-down area of 0.318734 and a diffusion area of 9.56607, please.", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.318734, 9.566071] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "If the slowing-down area is 0.671697 and the diffusion area is 14.2496, what is the migration area?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.671697, 14.249569] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Could you work out the migration area given slowing-down area = 0.671697, diffusion area = 14.2496?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [0.671697, 14.249569] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "I need the migration area for a slowing-down area of 21.7931 and a diffusion area of 29.5106, please.", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [21.793126, 29.510609] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "If the slowing-down area is 21.7931 and the diffusion area is 29.5106, what is the migration area?", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [21.793126, 29.510609] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "Could you work out the migration area given slowing-down area = 153.15, diffusion area = 18.5953?", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [153.149965, 18.595315] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "I need the migration area for a slowing-down area of 153.15 and a diffusion area of 18.5953, please.", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "m^2", + "why": "migration area for [153.149965, 18.595315] (the system migration area (Wikidata Q98966325))" + }, + { + "q": "If the slowing-down area is 8.50728, what is the migration area?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diffusion area is not given" + }, + { + "q": "Could you work out the migration area given slowing-down area = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the diffusion area is not given" + }, + { + "q": "Do you know the migration area 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 migration area 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 migration area given slowing-down area = -0.318734, diffusion area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative slowing-down area: no example had one" + }, + { + "q": "What is a typical migration area?", + "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-migration-area/program.py b/root/organs10/physics/specialists/solved-migration-area/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5df1de2f3294355137d12fad6586d59e1562811b --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area/program.py @@ -0,0 +1,7 @@ +"""migration area from slowing-down area, diffusion area (migration area (Wikidata Q98966325)) +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(slowing_down_area, diffusion_area): + return 1.0*diffusion_area + 1.0*slowing_down_area diff --git a/root/organs10/physics/specialists/solved-migration-area/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-migration-area/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-area/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-migration-length/organ_formula_v2.py b/root/organs10/physics/specialists/solved-migration-length/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-length/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-migration-length/panel.json b/root/organs10/physics/specialists/solved-migration-length/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..4433a4e0252e587d6a5e7726c661a1c1ad2e15cd --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-length/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the migration length for migration area 107.961?", + "a": "10.390412209819301", + "valid": true, + "kind": "compute", + "expect": 10.390412209819301, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [107.960666] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 107.961.", + "a": "10.390412209819301", + "valid": true, + "kind": "compute", + "expect": 10.390412209819301, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [107.960666] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length for migration area 22.652?", + "a": "4.759414123277758", + "valid": true, + "kind": "compute", + "expect": 4.759414123277758, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [22.652023] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 22.652.", + "a": "4.759414123277758", + "valid": true, + "kind": "compute", + "expect": 4.759414123277758, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [22.652023] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length for migration area 173.394?", + "a": "13.167901822435589", + "valid": true, + "kind": "compute", + "expect": 13.167901822435589, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [173.393638] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 173.394.", + "a": "13.167901822435589", + "valid": true, + "kind": "compute", + "expect": 13.167901822435589, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [173.393638] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length for migration area 126.709?", + "a": "11.25652041264006", + "valid": true, + "kind": "compute", + "expect": 11.25652041264006, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [126.709252] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 126.709.", + "a": "11.25652041264006", + "valid": true, + "kind": "compute", + "expect": 11.25652041264006, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [126.709252] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length for migration area 0.671697?", + "a": "0.8195713512527103", + "valid": true, + "kind": "compute", + "expect": 0.8195713512527103, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [0.671697] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 0.671697.", + "a": "0.8195713512527103", + "valid": true, + "kind": "compute", + "expect": 0.8195713512527103, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [0.671697] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length for migration area 1.16997?", + "a": "1.0816505932961604", + "valid": true, + "kind": "compute", + "expect": 1.0816505932961604, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [1.169968] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Tell me the migration length with migration area of 1.16997.", + "a": "1.0816505932961604", + "valid": true, + "kind": "compute", + "expect": 1.0816505932961604, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [1.169968] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "What is the migration length?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration area is not given" + }, + { + "q": "Could you work out the migration length, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration area is not given" + }, + { + "q": "What is the migration length 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 migration length 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 migration length with migration area of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative migration area: no example had one" + }, + { + "q": "Which migration length 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 migration area is 2.57003, what is the migration length?", + "a": "1.6031312838640646", + "valid": true, + "kind": "compute", + "expect": 1.6031312838640646, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [2.57003] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration length given migration area = 2.57003?", + "a": "1.6031312838640646", + "valid": true, + "kind": "compute", + "expect": 1.6031312838640646, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [2.57003] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration length for a migration area of 48.921, please.", + "a": "6.994354213221678", + "valid": true, + "kind": "compute", + "expect": 6.994354213221678, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [48.920991] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration area is 48.921, what is the migration length?", + "a": "6.994354213221678", + "valid": true, + "kind": "compute", + "expect": 6.994354213221678, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [48.920991] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration length given migration area = 0.348438?", + "a": "0.5902860913404876", + "valid": true, + "kind": "compute", + "expect": 0.5902860913404876, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [0.348438] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration length for a migration area of 0.348438, please.", + "a": "0.5902860913404876", + "valid": true, + "kind": "compute", + "expect": 0.5902860913404876, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [0.348438] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration area is 252.709, what is the migration length?", + "a": "15.896824344803195", + "valid": true, + "kind": "compute", + "expect": 15.896824344803195, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [252.709024] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration length given migration area = 252.709?", + "a": "15.896824344803195", + "valid": true, + "kind": "compute", + "expect": 15.896824344803195, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [252.709024] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration length for a migration area of 20.3966, please.", + "a": "4.516254860164939", + "valid": true, + "kind": "compute", + "expect": 4.516254860164939, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [20.396558] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "If the migration area is 20.3966, what is the migration length?", + "a": "4.516254860164939", + "valid": true, + "kind": "compute", + "expect": 4.516254860164939, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [20.396558] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "Could you work out the migration length given migration area = 134.993?", + "a": "11.618646977197388", + "valid": true, + "kind": "compute", + "expect": 11.618646977197388, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [134.992958] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration length for a migration area of 134.993, please.", + "a": "11.618646977197388", + "valid": true, + "kind": "compute", + "expect": 11.618646977197388, + "dtype": "quantity", + "unit": "m", + "why": "migration length for [134.992958] (the system migration length (Wikidata Q98998318))" + }, + { + "q": "I need the migration length, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration area is not given" + }, + { + "q": "Can you tell me the migration length?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the migration area is not given" + }, + { + "q": "Do you know the migration length 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 migration length 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 migration length given migration area = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative migration area: no example had one" + }, + { + "q": "What is a typical migration length?", + "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-migration-length/program.py b/root/organs10/physics/specialists/solved-migration-length/program.py new file mode 100644 index 0000000000000000000000000000000000000000..22b7ad720baca353c574ef3267d9fb6d9b0e32e8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-length/program.py @@ -0,0 +1,7 @@ +"""migration length from migration area (migration length (Wikidata Q98998318)) +The maths organ (systems.py): solved from the system q1 = sqrt(q0); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(migration_area): + return 1.0*migration_area**0.5 diff --git a/root/organs10/physics/specialists/solved-migration-length/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-migration-length/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-migration-length/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-mixing-ratio-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mixing-ratio-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio-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-mixing-ratio-2/panel.json b/root/organs10/physics/specialists/solved-mixing-ratio-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..758f7c9c7948b22c7672a78d8feeac2ea1fd78df --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 107.961 and relative mass ratio of vapour 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [107.960666, 59.4105] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 107.961 and relative mass ratio of vapour of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [107.960666, 59.4105] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 169.527 and relative mass ratio of vapour 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [169.526958, 280.773702] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 169.527 and relative mass ratio of vapour of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [169.526958, 280.773702] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 1.91195 and relative mass ratio of vapour 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.911952, 82.240072] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 1.91195 and relative mass ratio of vapour of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.911952, 82.240072] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 1.64379 and relative mass ratio of vapour 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.643795, 252.709024] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 1.64379 and relative mass ratio of vapour of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.643795, 252.709024] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 18.3169 and relative mass ratio of vapour 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [18.316867, 6.838598] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 18.3169 and relative mass ratio of vapour of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [18.316867, 6.838598] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio for mass ratio of water vapour to dry gas at saturation 156.502 and relative mass ratio of vapour 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [156.50181, 185.886273] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Tell me the mixing ratio with mass ratio of water vapour to dry gas at saturation of 156.502 and relative mass ratio of vapour of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [156.50181, 185.886273] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "What is the mixing ratio 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 relative mass ratio of vapour is not given" + }, + { + "q": "Tell me the mixing ratio 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 relative mass ratio of vapour is not given" + }, + { + "q": "What is the mixing 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 mixing 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 mixing ratio with mass ratio of water vapour to dry gas at saturation of -1.91195 and relative mass ratio of vapour 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 mixing 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 mass ratio of water vapour to dry gas at saturation is 8.50728 and the relative mass ratio of vapour is 17.7888, what is the mixing ratio?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.507283, 17.788778] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the mixing ratio given mass ratio of water vapour to dry gas at saturation = 8.50728, relative mass ratio of vapour = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.507283, 17.788778] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the mixing ratio for a mass ratio of water vapour to dry gas at saturation of 8.24951 and a relative mass ratio of vapour of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio 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 relative mass ratio of vapour is 0.634021, what is the mixing ratio?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.24951, 0.634021] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the mixing ratio given mass ratio of water vapour to dry gas at saturation = 0.318734, relative mass ratio of vapour = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.318734, 9.566071] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the mixing ratio for a mass ratio of water vapour to dry gas at saturation of 0.318734 and a relative mass ratio of vapour of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio 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 relative mass ratio of vapour is 14.2496, what is the mixing ratio?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.671697, 14.249569] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the mixing ratio given mass ratio of water vapour to dry gas at saturation = 0.671697, relative mass ratio of vapour = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.671697, 14.249569] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the mixing ratio for a mass ratio of water vapour to dry gas at saturation of 21.7931 and a relative mass ratio of vapour of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio 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 relative mass ratio of vapour is 29.5106, what is the mixing ratio?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [21.793126, 29.510609] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "Could you work out the mixing ratio given mass ratio of water vapour to dry gas at saturation = 153.15, relative mass ratio of vapour = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [153.149965, 18.595315] (the system relative mass ratio of vapour (Wikidata Q76379414))" + }, + { + "q": "I need the mixing ratio for a mass ratio of water vapour to dry gas at saturation of 153.15 and a relative mass ratio of vapour of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio 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 mixing ratio?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the relative mass ratio of vapour is not given" + }, + { + "q": "Could you work out the mixing ratio 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 relative mass ratio of vapour is not given" + }, + { + "q": "Do you know the mixing 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 mixing 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 mixing ratio given mass ratio of water vapour to dry gas at saturation = -0.318734, relative mass ratio of vapour = 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 mixing 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-mixing-ratio-2/program.py b/root/organs10/physics/specialists/solved-mixing-ratio-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..9e0735c944a21d4871e2d84df35a044b2ad79ceb --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio-2/program.py @@ -0,0 +1,7 @@ +"""mixing ratio from mass ratio of water vapour to dry gas at saturation, relative mass ratio of vapour (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, relative_mass_ratio_of_vapour): + return 1.0*mass_ratio_of_water_vapour_to_dry_gas_at_saturation*relative_mass_ratio_of_vapour diff --git a/root/organs10/physics/specialists/solved-mixing-ratio-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mixing-ratio-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio-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-mixing-ratio/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mixing-ratio/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-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-mixing-ratio/panel.json b/root/organs10/physics/specialists/solved-mixing-ratio/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..00e15be8b304cb3f06a46495bea6bfbe3037ce52 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mixing ratio for mass of dry gas 107.961 and mass of water vapour 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [107.960666, 59.4105] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 107.961 and mass of water vapour of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [107.960666, 59.4105] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 169.527 and mass of water vapour 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [169.526958, 280.773702] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 169.527 and mass of water vapour of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [169.526958, 280.773702] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 1.91195 and mass of water vapour 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.911952, 82.240072] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 1.91195 and mass of water vapour of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.911952, 82.240072] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 1.64379 and mass of water vapour 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.643795, 252.709024] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 1.64379 and mass of water vapour of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [1.643795, 252.709024] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 18.3169 and mass of water vapour 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [18.316867, 6.838598] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 18.3169 and mass of water vapour of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [18.316867, 6.838598] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 156.502 and mass of water vapour 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [156.50181, 185.886273] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 156.502 and mass of water vapour of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [156.50181, 185.886273] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "What is the mixing ratio for mass of dry gas 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of water vapour is not given" + }, + { + "q": "Tell me the mixing ratio with mass of dry gas of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of water vapour is not given" + }, + { + "q": "What is the mixing 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 mixing 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 mixing ratio with mass of dry gas of -1.91195 and mass of water vapour of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass of dry gas: no example had one" + }, + { + "q": "Which mixing 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 mass of dry gas is 8.50728 and the mass of water vapour is 17.7888, what is the mixing ratio?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.507283, 17.788778] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Could you work out the mixing ratio given mass of dry gas = 8.50728, mass of water vapour = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.507283, 17.788778] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "I need the mixing ratio for a mass of dry gas of 8.24951 and a mass of water vapour of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.24951, 0.634021] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "If the mass of dry gas is 8.24951 and the mass of water vapour is 0.634021, what is the mixing ratio?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [8.24951, 0.634021] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Could you work out the mixing ratio given mass of dry gas = 0.318734, mass of water vapour = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.318734, 9.566071] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "I need the mixing ratio for a mass of dry gas of 0.318734 and a mass of water vapour of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.318734, 9.566071] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "If the mass of dry gas is 0.671697 and the mass of water vapour is 14.2496, what is the mixing ratio?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.671697, 14.249569] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Could you work out the mixing ratio given mass of dry gas = 0.671697, mass of water vapour = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [0.671697, 14.249569] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "I need the mixing ratio for a mass of dry gas of 21.7931 and a mass of water vapour of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [21.793126, 29.510609] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "If the mass of dry gas is 21.7931 and the mass of water vapour is 29.5106, what is the mixing ratio?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [21.793126, 29.510609] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "Could you work out the mixing ratio given mass of dry gas = 153.15, mass of water vapour = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [153.149965, 18.595315] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "I need the mixing ratio for a mass of dry gas of 153.15 and a mass of water vapour of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1", + "why": "mixing ratio for [153.149965, 18.595315] (the system mixing ratio (Wikidata Q17232415))" + }, + { + "q": "If the mass of dry gas is 8.50728, what is the mixing ratio?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of water vapour is not given" + }, + { + "q": "Could you work out the mixing ratio given mass of dry gas = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of water vapour is not given" + }, + { + "q": "Do you know the mixing 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 mixing 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 mixing ratio given mass of dry gas = -0.318734, mass of water vapour = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative mass of dry gas: no example had one" + }, + { + "q": "What is a typical mixing 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-mixing-ratio/program.py b/root/organs10/physics/specialists/solved-mixing-ratio/program.py new file mode 100644 index 0000000000000000000000000000000000000000..7441b7aef148aadb5e8b4405fb7f266a67c6e4ad --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-ratio/program.py @@ -0,0 +1,7 @@ +"""mixing ratio from mass of dry gas, mass of water vapour (mixing ratio (Wikidata Q17232415)) +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_of_dry_gas, mass_of_water_vapour): + return 1.0*mass_of_water_vapour/mass_of_dry_gas diff --git a/root/organs10/physics/specialists/solved-mixing-ratio/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mixing-ratio/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mixing-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-mobility/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mobility/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mobility/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-mobility/panel.json b/root/organs10/physics/specialists/solved-mobility/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..490518c53b26c5ff07a6d3b950aac3ee7dd3943c --- /dev/null +++ b/root/organs10/physics/specialists/solved-mobility/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mobility for drift velocity 107.961 and electric field strength 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [107.960666, 59.4105] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 107.961 and electric field strength of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [107.960666, 59.4105] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 169.527 and electric field strength 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [169.526958, 280.773702] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 169.527 and electric field strength of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [169.526958, 280.773702] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 1.91195 and electric field strength 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [1.911952, 82.240072] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 1.91195 and electric field strength of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [1.911952, 82.240072] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 1.64379 and electric field strength 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [1.643795, 252.709024] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 1.64379 and electric field strength of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [1.643795, 252.709024] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 18.3169 and electric field strength 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [18.316867, 6.838598] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 18.3169 and electric field strength of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [18.316867, 6.838598] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 156.502 and electric field strength 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [156.50181, 185.886273] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Tell me the mobility with drift velocity of 156.502 and electric field strength of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [156.50181, 185.886273] (the system mobility (Wikidata Q900648))" + }, + { + "q": "What is the mobility for drift velocity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Tell me the mobility with drift velocity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "What is the mobility 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 mobility 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 mobility with drift velocity of -1.91195 and electric field strength of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative drift velocity: no example had one" + }, + { + "q": "Which mobility 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 drift velocity is 8.50728 and the electric field strength is 17.7888, what is the mobility?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [8.507283, 17.788778] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Could you work out the mobility given drift velocity = 8.50728, electric field strength = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [8.507283, 17.788778] (the system mobility (Wikidata Q900648))" + }, + { + "q": "I need the mobility for a drift velocity of 8.24951 and an electric field strength of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [8.24951, 0.634021] (the system mobility (Wikidata Q900648))" + }, + { + "q": "If the drift velocity is 8.24951 and the electric field strength is 0.634021, what is the mobility?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [8.24951, 0.634021] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Could you work out the mobility given drift velocity = 0.318734, electric field strength = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [0.318734, 9.566071] (the system mobility (Wikidata Q900648))" + }, + { + "q": "I need the mobility for a drift velocity of 0.318734 and an electric field strength of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [0.318734, 9.566071] (the system mobility (Wikidata Q900648))" + }, + { + "q": "If the drift velocity is 0.671697 and the electric field strength is 14.2496, what is the mobility?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [0.671697, 14.249569] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Could you work out the mobility given drift velocity = 0.671697, electric field strength = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [0.671697, 14.249569] (the system mobility (Wikidata Q900648))" + }, + { + "q": "I need the mobility for a drift velocity of 21.7931 and an electric field strength of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [21.793126, 29.510609] (the system mobility (Wikidata Q900648))" + }, + { + "q": "If the drift velocity is 21.7931 and the electric field strength is 29.5106, what is the mobility?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [21.793126, 29.510609] (the system mobility (Wikidata Q900648))" + }, + { + "q": "Could you work out the mobility given drift velocity = 153.15, electric field strength = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [153.149965, 18.595315] (the system mobility (Wikidata Q900648))" + }, + { + "q": "I need the mobility for a drift velocity of 153.15 and an electric field strength of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s^2*A/kg", + "why": "mobility for [153.149965, 18.595315] (the system mobility (Wikidata Q900648))" + }, + { + "q": "If the drift velocity is 8.50728, what is the mobility?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Could you work out the mobility given drift velocity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Do you know the mobility 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 mobility 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 mobility given drift velocity = -0.318734, electric field strength = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative drift velocity: no example had one" + }, + { + "q": "What is a typical mobility?", + "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-mobility/program.py b/root/organs10/physics/specialists/solved-mobility/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f5b581406d049ab6811deb444d57b99ce9aa7c --- /dev/null +++ b/root/organs10/physics/specialists/solved-mobility/program.py @@ -0,0 +1,7 @@ +"""mobility from drift velocity, electric field strength (mobility (Wikidata Q900648)) +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(drift_velocity, electric_field_strength): + return 1.0*drift_velocity/electric_field_strength diff --git a/root/organs10/physics/specialists/solved-mobility/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mobility/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mobility/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-molality-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molality-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality-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-molality-2/panel.json b/root/organs10/physics/specialists/solved-molality-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ece6f8a3967da6bcddb58d16b25950e0b336a066 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molality for standard molality 107.961, activity coefficient 59.4105 and activity of solute 5.77717?", + "a": "10.498254293702432", + "valid": true, + "kind": "compute", + "expect": 10.498254293702432, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [107.960666, 59.4105, 5.777165] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 107.961, activity coefficient of 59.4105 and activity of solute of 5.77717.", + "a": "10.498254293702432", + "valid": true, + "kind": "compute", + "expect": 10.498254293702432, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [107.960666, 59.4105, 5.777165] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 85.2416, activity coefficient 160.878 and activity of solute 2.69428?", + "a": "1.4275672119863798", + "valid": true, + "kind": "compute", + "expect": 1.4275672119863798, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [85.241623, 160.878442, 2.69428] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 85.2416, activity coefficient of 160.878 and activity of solute of 2.69428.", + "a": "1.4275672119863798", + "valid": true, + "kind": "compute", + "expect": 1.4275672119863798, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [85.241623, 160.878442, 2.69428] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 45.6157, activity coefficient 4.97131 and activity of solute 94.305?", + "a": "865.3232325447225", + "valid": true, + "kind": "compute", + "expect": 865.3232325447225, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [45.61567, 4.971307, 94.305046] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 45.6157, activity coefficient of 4.97131 and activity of solute of 94.305.", + "a": "865.3232325447225", + "valid": true, + "kind": "compute", + "expect": 865.3232325447225, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [45.61567, 4.971307, 94.305046] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 10.5638, activity coefficient 198.839 and activity of solute 0.671697?", + "a": "0.03568568130708054", + "valid": true, + "kind": "compute", + "expect": 0.03568568130708054, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [10.563843, 198.838955, 0.671697] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 10.5638, activity coefficient of 198.839 and activity of solute of 0.671697.", + "a": "0.03568568130708054", + "valid": true, + "kind": "compute", + "expect": 0.03568568130708054, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [10.563843, 198.838955, 0.671697] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 21.7931, activity coefficient 29.5106 and activity of solute 8.50341?", + "a": "6.279634237980215", + "valid": true, + "kind": "compute", + "expect": 6.279634237980215, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.793126, 29.510609, 8.503407] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 21.7931, activity coefficient of 29.5106 and activity of solute of 8.50341.", + "a": "6.279634237980215", + "valid": true, + "kind": "compute", + "expect": 6.279634237980215, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.793126, 29.510609, 8.503407] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 223.509, activity coefficient 17.3414 and activity of solute 7.10705?", + "a": "91.60072422473009", + "valid": true, + "kind": "compute", + "expect": 91.60072422473009, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [223.508796, 17.341435, 7.107049] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Tell me the molality with standard molality of 223.509, activity coefficient of 17.3414 and activity of solute of 7.10705.", + "a": "91.60072422473009", + "valid": true, + "kind": "compute", + "expect": 91.60072422473009, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [223.508796, 17.341435, 7.107049] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "What is the molality for standard molality 107.961 and activity coefficient 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the activity of solute is not given" + }, + { + "q": "Tell me the molality with standard molality of 85.2416 and activity coefficient of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the activity of solute is not given" + }, + { + "q": "What is the molality 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 molality 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 molality with standard molality of -45.6157, activity coefficient of 4.97131 and activity of solute of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative standard molality: no example had one" + }, + { + "q": "Which molality 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 standard molality is 17.7888, activity coefficient is 167.625 and the activity of solute is 10.3291, what is the molality?", + "a": "1.0961450581531387", + "valid": true, + "kind": "compute", + "expect": 1.0961450581531387, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [17.788778, 167.624948, 10.329054] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Could you work out the molality given standard molality = 17.7888, activity coefficient = 167.625, activity of solute = 10.3291?", + "a": "1.0961450581531387", + "valid": true, + "kind": "compute", + "expect": 1.0961450581531387, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [17.788778, 167.624948, 10.329054] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "I need the molality for a standard molality of 21.511, an activity coefficient of 173.394 and an activity of solute of 251.084, please.", + "a": "31.149197612202414", + "valid": true, + "kind": "compute", + "expect": 31.149197612202414, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.511016, 173.393638, 251.084037] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "If the standard molality is 21.511, activity coefficient is 173.394 and the activity of solute is 251.084, what is the molality?", + "a": "31.149197612202414", + "valid": true, + "kind": "compute", + "expect": 31.149197612202414, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.511016, 173.393638, 251.084037] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Could you work out the molality given standard molality = 129.245, activity coefficient = 1.18359, activity of solute = 15.9416?", + "a": "1740.7830274187056", + "valid": true, + "kind": "compute", + "expect": 1740.7830274187056, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [129.244984, 1.18359, 15.941612] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "I need the molality for a standard molality of 129.245, an activity coefficient of 1.18359 and an activity of solute of 15.9416, please.", + "a": "1740.7830274187056", + "valid": true, + "kind": "compute", + "expect": 1740.7830274187056, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [129.244984, 1.18359, 15.941612] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "If the standard molality is 20.3966, activity coefficient is 18.3169 and the activity of solute is 6.8386, what is the molality?", + "a": "7.615050191987504", + "valid": true, + "kind": "compute", + "expect": 7.615050191987504, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [20.396558, 18.316867, 6.838598] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Could you work out the molality given standard molality = 20.3966, activity coefficient = 18.3169, activity of solute = 6.8386?", + "a": "7.615050191987504", + "valid": true, + "kind": "compute", + "expect": 7.615050191987504, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [20.396558, 18.316867, 6.838598] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "I need the molality for a standard molality of 185.886, an activity coefficient of 13.2373 and an activity of solute of 4.71941, please.", + "a": "66.27285731134774", + "valid": true, + "kind": "compute", + "expect": 66.27285731134774, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [185.886273, 13.237311, 4.719415] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "If the standard molality is 185.886, activity coefficient is 13.2373 and the activity of solute is 4.71941, what is the molality?", + "a": "66.27285731134774", + "valid": true, + "kind": "compute", + "expect": 66.27285731134774, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [185.886273, 13.237311, 4.719415] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "Could you work out the molality given standard molality = 9.1061, activity coefficient = 24.5721, activity of solute = 108.451?", + "a": "40.19049097830896", + "valid": true, + "kind": "compute", + "expect": 40.19049097830896, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [9.106104, 24.572086, 108.450792] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "I need the molality for a standard molality of 9.1061, an activity coefficient of 24.5721 and an activity of solute of 108.451, please.", + "a": "40.19049097830896", + "valid": true, + "kind": "compute", + "expect": 40.19049097830896, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [9.106104, 24.572086, 108.450792] (the system activity coefficient (Wikidata Q745224))" + }, + { + "q": "If the standard molality is 17.7888 and the activity coefficient is 167.625, what is the molality?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the activity of solute is not given" + }, + { + "q": "Could you work out the molality given standard molality = 21.511, activity coefficient = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the activity of solute is not given" + }, + { + "q": "Do you know the molality 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 molality 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 molality given standard molality = -129.245, activity coefficient = 1.18359, activity of solute = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative standard molality: no example had one" + }, + { + "q": "What is a typical molality?", + "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-molality-2/program.py b/root/organs10/physics/specialists/solved-molality-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5f67f3525c697a66aae5f4ded04d4697a90f8a68 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality-2/program.py @@ -0,0 +1,7 @@ +"""molality from standard molality, activity coefficient, activity of solute (activity coefficient (Wikidata Q745224)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q3 / q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(standard_molality, activity_coefficient, activity_of_solute): + return 1.0*activity_of_solute*standard_molality/activity_coefficient diff --git a/root/organs10/physics/specialists/solved-molality-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molality-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality-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-molality/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molality/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality/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-molality/panel.json b/root/organs10/physics/specialists/solved-molality/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..543c9c78df145bcb31d3213250000aa3812b8e13 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molality for amount of substance of component 107.961 and mass of component 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [107.960666, 59.4105] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 107.961 and mass of component of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [107.960666, 59.4105] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 169.527 and mass of component 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [169.526958, 280.773702] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 169.527 and mass of component of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [169.526958, 280.773702] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 1.91195 and mass of component 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [1.911952, 82.240072] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 1.91195 and mass of component of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [1.911952, 82.240072] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 1.64379 and mass of component 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [1.643795, 252.709024] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 1.64379 and mass of component of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [1.643795, 252.709024] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 18.3169 and mass of component 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [18.316867, 6.838598] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 18.3169 and mass of component of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [18.316867, 6.838598] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 156.502 and mass of component 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [156.50181, 185.886273] (the system molality (Wikidata Q172623))" + }, + { + "q": "Tell me the molality with amount of substance of component of 156.502 and mass of component of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [156.50181, 185.886273] (the system molality (Wikidata Q172623))" + }, + { + "q": "What is the molality for amount of substance of component 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of component is not given" + }, + { + "q": "Tell me the molality with amount of substance of component of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of component is not given" + }, + { + "q": "What is the molality 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 molality 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 molality with amount of substance of component of -1.91195 and mass of component of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount of substance of component: no example had one" + }, + { + "q": "Which molality 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 amount of substance of component is 8.50728 and the mass of component is 17.7888, what is the molality?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [8.507283, 17.788778] (the system molality (Wikidata Q172623))" + }, + { + "q": "Could you work out the molality given amount of substance of component = 8.50728, mass of component = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [8.507283, 17.788778] (the system molality (Wikidata Q172623))" + }, + { + "q": "I need the molality for an amount of substance of component of 8.24951 and a mass of component of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [8.24951, 0.634021] (the system molality (Wikidata Q172623))" + }, + { + "q": "If the amount of substance of component is 8.24951 and the mass of component is 0.634021, what is the molality?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [8.24951, 0.634021] (the system molality (Wikidata Q172623))" + }, + { + "q": "Could you work out the molality given amount of substance of component = 0.318734, mass of component = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [0.318734, 9.566071] (the system molality (Wikidata Q172623))" + }, + { + "q": "I need the molality for an amount of substance of component of 0.318734 and a mass of component of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [0.318734, 9.566071] (the system molality (Wikidata Q172623))" + }, + { + "q": "If the amount of substance of component is 0.671697 and the mass of component is 14.2496, what is the molality?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [0.671697, 14.249569] (the system molality (Wikidata Q172623))" + }, + { + "q": "Could you work out the molality given amount of substance of component = 0.671697, mass of component = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [0.671697, 14.249569] (the system molality (Wikidata Q172623))" + }, + { + "q": "I need the molality for an amount of substance of component of 21.7931 and a mass of component of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.793126, 29.510609] (the system molality (Wikidata Q172623))" + }, + { + "q": "If the amount of substance of component is 21.7931 and the mass of component is 29.5106, what is the molality?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [21.793126, 29.510609] (the system molality (Wikidata Q172623))" + }, + { + "q": "Could you work out the molality given amount of substance of component = 153.15, mass of component = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [153.149965, 18.595315] (the system molality (Wikidata Q172623))" + }, + { + "q": "I need the molality for an amount of substance of component of 153.15 and a mass of component of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "mol/kg", + "why": "molality for [153.149965, 18.595315] (the system molality (Wikidata Q172623))" + }, + { + "q": "If the amount of substance of component is 8.50728, what is the molality?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of component is not given" + }, + { + "q": "Could you work out the molality given amount of substance of component = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass of component is not given" + }, + { + "q": "Do you know the molality 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 molality 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 molality given amount of substance of component = -0.318734, mass of component = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount of substance of component: no example had one" + }, + { + "q": "What is a typical molality?", + "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-molality/program.py b/root/organs10/physics/specialists/solved-molality/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4a459a3bd253dd4a4a34a8b9ec85be6b18ee82 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality/program.py @@ -0,0 +1,7 @@ +"""molality from amount of substance of component, mass of component (molality (Wikidata Q172623)) +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(amount_of_substance_of_component, mass_of_component): + return 1.0*amount_of_substance_of_component/mass_of_component diff --git a/root/organs10/physics/specialists/solved-molality/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molality/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molality/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-molar-attenuation-coefficient/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/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-molar-attenuation-coefficient/panel.json b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..542e819b08e2b40c34250fd87319038ad1b4fb72 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 107.961 and amount-of-substance concentration 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [107.960666, 59.4105] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 107.961 and amount-of-substance concentration of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [107.960666, 59.4105] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 169.527 and amount-of-substance concentration 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [169.526958, 280.773702] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 169.527 and amount-of-substance concentration of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [169.526958, 280.773702] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 1.91195 and amount-of-substance concentration 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [1.911952, 82.240072] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 1.91195 and amount-of-substance concentration of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [1.911952, 82.240072] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 1.64379 and amount-of-substance concentration 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [1.643795, 252.709024] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 1.64379 and amount-of-substance concentration of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [1.643795, 252.709024] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 18.3169 and amount-of-substance concentration 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [18.316867, 6.838598] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 18.3169 and amount-of-substance concentration of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [18.316867, 6.838598] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 156.502 and amount-of-substance concentration 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [156.50181, 185.886273] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 156.502 and amount-of-substance concentration of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [156.50181, 185.886273] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "What is the molar attenuation coefficient for linear attenuation coefficient 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Tell me the molar attenuation coefficient with linear attenuation coefficient of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "What is the molar attenuation coefficient 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 molar attenuation coefficient 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 molar attenuation coefficient with linear attenuation coefficient of -1.91195 and amount-of-substance concentration of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative linear attenuation coefficient: no example had one" + }, + { + "q": "Which molar attenuation coefficient 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 linear attenuation coefficient is 8.50728 and the amount-of-substance concentration is 17.7888, what is the molar attenuation coefficient?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [8.507283, 17.788778] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Could you work out the molar attenuation coefficient given linear attenuation coefficient = 8.50728, amount-of-substance concentration = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [8.507283, 17.788778] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "I need the molar attenuation coefficient for a linear attenuation coefficient of 8.24951 and an amount-of-substance concentration of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [8.24951, 0.634021] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "If the linear attenuation coefficient is 8.24951 and the amount-of-substance concentration is 0.634021, what is the molar attenuation coefficient?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [8.24951, 0.634021] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Could you work out the molar attenuation coefficient given linear attenuation coefficient = 0.318734, amount-of-substance concentration = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [0.318734, 9.566071] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "I need the molar attenuation coefficient for a linear attenuation coefficient of 0.318734 and an amount-of-substance concentration of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [0.318734, 9.566071] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "If the linear attenuation coefficient is 0.671697 and the amount-of-substance concentration is 14.2496, what is the molar attenuation coefficient?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [0.671697, 14.249569] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Could you work out the molar attenuation coefficient given linear attenuation coefficient = 0.671697, amount-of-substance concentration = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [0.671697, 14.249569] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "I need the molar attenuation coefficient for a linear attenuation coefficient of 21.7931 and an amount-of-substance concentration of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [21.793126, 29.510609] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "If the linear attenuation coefficient is 21.7931 and the amount-of-substance concentration is 29.5106, what is the molar attenuation coefficient?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [21.793126, 29.510609] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "Could you work out the molar attenuation coefficient given linear attenuation coefficient = 153.15, amount-of-substance concentration = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [153.149965, 18.595315] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "I need the molar attenuation coefficient for a linear attenuation coefficient of 153.15 and an amount-of-substance concentration of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar attenuation coefficient for [153.149965, 18.595315] (the system molar attenuation coefficient (Wikidata Q98592828))" + }, + { + "q": "If the linear attenuation coefficient is 8.50728, what is the molar attenuation coefficient?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Could you work out the molar attenuation coefficient given linear attenuation coefficient = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Do you know the molar attenuation coefficient 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 molar attenuation coefficient 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 molar attenuation coefficient given linear attenuation coefficient = -0.318734, amount-of-substance concentration = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative linear attenuation coefficient: no example had one" + }, + { + "q": "What is a typical molar attenuation coefficient?", + "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-molar-attenuation-coefficient/program.py b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/program.py new file mode 100644 index 0000000000000000000000000000000000000000..531e45201e475996097d4b448812dbebf2f91be2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/program.py @@ -0,0 +1,7 @@ +"""molar attenuation coefficient from linear attenuation coefficient, amount-of-substance concentration (molar attenuation coefficient (Wikidata Q98592828)) +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(linear_attenuation_coefficient, amount_of_substance_concentration): + return 1.0*linear_attenuation_coefficient/amount_of_substance_concentration diff --git a/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-attenuation-coefficient/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-molar-conductivity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-conductivity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-conductivity/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-molar-conductivity/panel.json b/root/organs10/physics/specialists/solved-molar-conductivity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c11fc4f311fedfcde90a4e6594b099d574d191e8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-conductivity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar conductivity for amount-of-substance concentration 107.961 and electrolytic conductivity 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [107.960666, 59.4105] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 107.961 and electrolytic conductivity of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [107.960666, 59.4105] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 169.527 and electrolytic conductivity 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [169.526958, 280.773702] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 169.527 and electrolytic conductivity of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [169.526958, 280.773702] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 1.91195 and electrolytic conductivity 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [1.911952, 82.240072] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 1.91195 and electrolytic conductivity of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [1.911952, 82.240072] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 1.64379 and electrolytic conductivity 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [1.643795, 252.709024] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 1.64379 and electrolytic conductivity of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [1.643795, 252.709024] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 18.3169 and electrolytic conductivity 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [18.316867, 6.838598] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 18.3169 and electrolytic conductivity of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [18.316867, 6.838598] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 156.502 and electrolytic conductivity 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [156.50181, 185.886273] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 156.502 and electrolytic conductivity of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [156.50181, 185.886273] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "What is the molar conductivity for amount-of-substance concentration 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electrolytic conductivity is not given" + }, + { + "q": "Tell me the molar conductivity with amount-of-substance concentration of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electrolytic conductivity is not given" + }, + { + "q": "What is the molar conductivity 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 molar conductivity 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 molar conductivity with amount-of-substance concentration of -1.91195 and electrolytic conductivity of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount-of-substance concentration: no example had one" + }, + { + "q": "Which molar conductivity 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 amount-of-substance concentration is 8.50728 and the electrolytic conductivity is 17.7888, what is the molar conductivity?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [8.507283, 17.788778] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Could you work out the molar conductivity given amount-of-substance concentration = 8.50728, electrolytic conductivity = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [8.507283, 17.788778] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "I need the molar conductivity for an amount-of-substance concentration of 8.24951 and an electrolytic conductivity of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [8.24951, 0.634021] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "If the amount-of-substance concentration is 8.24951 and the electrolytic conductivity is 0.634021, what is the molar conductivity?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [8.24951, 0.634021] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Could you work out the molar conductivity given amount-of-substance concentration = 0.318734, electrolytic conductivity = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [0.318734, 9.566071] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "I need the molar conductivity for an amount-of-substance concentration of 0.318734 and an electrolytic conductivity of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [0.318734, 9.566071] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "If the amount-of-substance concentration is 0.671697 and the electrolytic conductivity is 14.2496, what is the molar conductivity?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [0.671697, 14.249569] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Could you work out the molar conductivity given amount-of-substance concentration = 0.671697, electrolytic conductivity = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [0.671697, 14.249569] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "I need the molar conductivity for an amount-of-substance concentration of 21.7931 and an electrolytic conductivity of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [21.793126, 29.510609] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "If the amount-of-substance concentration is 21.7931 and the electrolytic conductivity is 29.5106, what is the molar conductivity?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [21.793126, 29.510609] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "Could you work out the molar conductivity given amount-of-substance concentration = 153.15, electrolytic conductivity = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [153.149965, 18.595315] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "I need the molar conductivity for an amount-of-substance concentration of 153.15 and an electrolytic conductivity of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "s^3*A^2/kg/mol", + "why": "molar conductivity for [153.149965, 18.595315] (the system molar conductivity (Wikidata Q1943278))" + }, + { + "q": "If the amount-of-substance concentration is 8.50728, what is the molar conductivity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electrolytic conductivity is not given" + }, + { + "q": "Could you work out the molar conductivity given amount-of-substance concentration = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electrolytic conductivity is not given" + }, + { + "q": "Do you know the molar conductivity 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 molar conductivity 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 molar conductivity given amount-of-substance concentration = -0.318734, electrolytic conductivity = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount-of-substance concentration: no example had one" + }, + { + "q": "What is a typical molar conductivity?", + "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-molar-conductivity/program.py b/root/organs10/physics/specialists/solved-molar-conductivity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5c6edc48c7746f19381ba55dfffc5f966d80c8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-conductivity/program.py @@ -0,0 +1,7 @@ +"""molar conductivity from amount-of-substance concentration, electrolytic conductivity (molar conductivity (Wikidata Q1943278)) +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(amount_of_substance_concentration, electrolytic_conductivity): + return 1.0*electrolytic_conductivity/amount_of_substance_concentration diff --git a/root/organs10/physics/specialists/solved-molar-conductivity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-conductivity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-conductivity/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-molar-enthalpy-of-fusion/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/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-molar-enthalpy-of-fusion/panel.json b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..300e7bfa5d9bcf0dbf1329b3e710556446a209ef --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [107.960666, 59.4105] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [107.960666, 59.4105] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [169.526958, 280.773702] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [169.526958, 280.773702] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [1.911952, 82.240072] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [1.911952, 82.240072] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [1.643795, 252.709024] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [1.643795, 252.709024] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [18.316867, 6.838598] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [18.316867, 6.838598] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [156.50181, 185.886273] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Tell me the molar enthalpy of fusion with enthalpy of fusion of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [156.50181, 185.886273] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "What is the molar enthalpy of fusion for enthalpy of fusion 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 molar enthalpy of fusion with enthalpy of fusion 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 molar enthalpy of fusion 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 molar enthalpy of fusion 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 molar enthalpy of fusion with enthalpy of fusion 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 enthalpy of fusion: no example had one" + }, + { + "q": "Which molar enthalpy of fusion 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 of fusion is 8.50728 and the amount of substance is 17.7888, what is the molar enthalpy of fusion?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [8.507283, 17.788778] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Could you work out the molar enthalpy of fusion given enthalpy of fusion = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [8.507283, 17.788778] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "I need the molar enthalpy of fusion for an enthalpy of fusion of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [8.24951, 0.634021] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "If the enthalpy of fusion is 8.24951 and the amount of substance is 0.634021, what is the molar enthalpy of fusion?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [8.24951, 0.634021] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Could you work out the molar enthalpy of fusion given enthalpy of fusion = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [0.318734, 9.566071] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "I need the molar enthalpy of fusion for an enthalpy of fusion of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [0.318734, 9.566071] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "If the enthalpy of fusion is 0.671697 and the amount of substance is 14.2496, what is the molar enthalpy of fusion?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [0.671697, 14.249569] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Could you work out the molar enthalpy of fusion given enthalpy of fusion = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [0.671697, 14.249569] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "I need the molar enthalpy of fusion for an enthalpy of fusion of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [21.793126, 29.510609] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "If the enthalpy of fusion is 21.7931 and the amount of substance is 29.5106, what is the molar enthalpy of fusion?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [21.793126, 29.510609] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "Could you work out the molar enthalpy of fusion given enthalpy of fusion = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [153.149965, 18.595315] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "I need the molar enthalpy of fusion for an enthalpy of fusion of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy of fusion for [153.149965, 18.595315] (the system molar enthalpy of fusion (Wikidata Q108858279))" + }, + { + "q": "If the enthalpy of fusion is 8.50728, what is the molar enthalpy of fusion?", + "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 molar enthalpy of fusion given enthalpy of fusion = 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 molar enthalpy of fusion 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 molar enthalpy of fusion 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 molar enthalpy of fusion given enthalpy of fusion = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative enthalpy of fusion: no example had one" + }, + { + "q": "What is a typical molar enthalpy of fusion?", + "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-molar-enthalpy-of-fusion/program.py b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2cb0b9267cb81909b7f1ba50784129bc53310f --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/program.py @@ -0,0 +1,7 @@ +"""molar enthalpy of fusion from enthalpy of fusion, amount of substance (molar enthalpy of fusion (Wikidata Q108858279)) +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(enthalpy_of_fusion, amount_of_substance): + return 1.0*enthalpy_of_fusion/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy-of-fusion/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-molar-enthalpy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-enthalpy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy/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-molar-enthalpy/panel.json b/root/organs10/physics/specialists/solved-molar-enthalpy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5d32d1bb2f7b032740eb534a97b480fcfca0cbac --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar enthalpy for enthalpy 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [107.960666, 59.4105] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [107.960666, 59.4105] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [169.526958, 280.773702] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [169.526958, 280.773702] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [1.911952, 82.240072] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [1.911952, 82.240072] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [1.643795, 252.709024] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [1.643795, 252.709024] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [18.316867, 6.838598] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [18.316867, 6.838598] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [156.50181, 185.886273] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Tell me the molar enthalpy with enthalpy of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [156.50181, 185.886273] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "What is the molar enthalpy for enthalpy 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 molar enthalpy with enthalpy 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 molar enthalpy 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 molar enthalpy 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 molar enthalpy with enthalpy 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 enthalpy: no example had one" + }, + { + "q": "Which molar enthalpy 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.50728 and the amount of substance is 17.7888, what is the molar enthalpy?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [8.507283, 17.788778] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Could you work out the molar enthalpy given enthalpy = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [8.507283, 17.788778] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "I need the molar enthalpy for an enthalpy of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [8.24951, 0.634021] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "If the enthalpy is 8.24951 and the amount of substance is 0.634021, what is the molar enthalpy?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [8.24951, 0.634021] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Could you work out the molar enthalpy given enthalpy = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [0.318734, 9.566071] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "I need the molar enthalpy for an enthalpy of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [0.318734, 9.566071] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "If the enthalpy is 0.671697 and the amount of substance is 14.2496, what is the molar enthalpy?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [0.671697, 14.249569] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Could you work out the molar enthalpy given enthalpy = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [0.671697, 14.249569] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "I need the molar enthalpy for an enthalpy of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [21.793126, 29.510609] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "If the enthalpy is 21.7931 and the amount of substance is 29.5106, what is the molar enthalpy?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [21.793126, 29.510609] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "Could you work out the molar enthalpy given enthalpy = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [153.149965, 18.595315] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "I need the molar enthalpy for an enthalpy of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar enthalpy for [153.149965, 18.595315] (the system molar enthalpy (Wikidata Q88769977))" + }, + { + "q": "If the enthalpy is 8.50728, what is the molar enthalpy?", + "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 molar enthalpy given enthalpy = 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 molar enthalpy 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 molar enthalpy 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 molar enthalpy given enthalpy = -0.318734, amount of substance = 9.56607?", + "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 molar enthalpy?", + "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-molar-enthalpy/program.py b/root/organs10/physics/specialists/solved-molar-enthalpy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c853e854033b7ea9b4e08c96e90209f1f24f7f75 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy/program.py @@ -0,0 +1,7 @@ +"""molar enthalpy from enthalpy, amount of substance (molar enthalpy (Wikidata Q88769977)) +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(enthalpy, amount_of_substance): + return 1.0*enthalpy/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-enthalpy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-enthalpy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-enthalpy/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-molar-entropy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-entropy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-entropy/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-molar-entropy/panel.json b/root/organs10/physics/specialists/solved-molar-entropy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5323b8596635c94ea64c40a29f1dbebd483c3788 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-entropy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar entropy for entropy 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [107.960666, 59.4105] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [107.960666, 59.4105] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [169.526958, 280.773702] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [169.526958, 280.773702] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [1.911952, 82.240072] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [1.911952, 82.240072] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [1.643795, 252.709024] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [1.643795, 252.709024] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [18.316867, 6.838598] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [18.316867, 6.838598] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [156.50181, 185.886273] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Tell me the molar entropy with entropy of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [156.50181, 185.886273] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "What is the molar entropy for entropy 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 molar entropy with entropy 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 molar entropy 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 molar entropy 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 molar entropy with entropy 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 entropy: no example had one" + }, + { + "q": "Which molar entropy 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 entropy is 8.50728 and the amount of substance is 17.7888, what is the molar entropy?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [8.507283, 17.788778] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Could you work out the molar entropy given entropy = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [8.507283, 17.788778] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "I need the molar entropy for an entropy of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [8.24951, 0.634021] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "If the entropy is 8.24951 and the amount of substance is 0.634021, what is the molar entropy?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [8.24951, 0.634021] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Could you work out the molar entropy given entropy = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [0.318734, 9.566071] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "I need the molar entropy for an entropy of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [0.318734, 9.566071] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "If the entropy is 0.671697 and the amount of substance is 14.2496, what is the molar entropy?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [0.671697, 14.249569] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Could you work out the molar entropy given entropy = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [0.671697, 14.249569] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "I need the molar entropy for an entropy of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [21.793126, 29.510609] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "If the entropy is 21.7931 and the amount of substance is 29.5106, what is the molar entropy?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [21.793126, 29.510609] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "Could you work out the molar entropy given entropy = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [153.149965, 18.595315] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "I need the molar entropy for an entropy of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar entropy for [153.149965, 18.595315] (the system molar entropy (Wikidata Q68972876))" + }, + { + "q": "If the entropy is 8.50728, what is the molar entropy?", + "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 molar entropy given entropy = 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 molar entropy 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 molar entropy 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 molar entropy given entropy = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative entropy: no example had one" + }, + { + "q": "What is a typical molar entropy?", + "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-molar-entropy/program.py b/root/organs10/physics/specialists/solved-molar-entropy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..741510f5f18a5e48c6da5432e57eb1fbeaa3cbb7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-entropy/program.py @@ -0,0 +1,7 @@ +"""molar entropy from entropy, amount of substance (molar entropy (Wikidata Q68972876)) +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(entropy, amount_of_substance): + return 1.0*entropy/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-entropy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-entropy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-entropy/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-molar-gibbs-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-gibbs-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-gibbs-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-molar-gibbs-energy/panel.json b/root/organs10/physics/specialists/solved-molar-gibbs-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ce48c7e732b8c17f6546e83e22126b38bac7d9f6 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-gibbs-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar Gibbs energy for Gibbs free energy 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [107.960666, 59.4105] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [107.960666, 59.4105] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [169.526958, 280.773702] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [169.526958, 280.773702] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [1.911952, 82.240072] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [1.911952, 82.240072] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [1.643795, 252.709024] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [1.643795, 252.709024] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [18.316867, 6.838598] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [18.316867, 6.838598] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [156.50181, 185.886273] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Tell me the molar Gibbs energy with Gibbs free energy of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [156.50181, 185.886273] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "What is the molar Gibbs energy for Gibbs free energy 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 molar Gibbs energy with Gibbs free energy 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 molar Gibbs 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 molar Gibbs 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 molar Gibbs energy with Gibbs free energy 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 Gibbs free energy: no example had one" + }, + { + "q": "Which molar Gibbs 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 Gibbs free energy is 8.50728 and the amount of substance is 17.7888, what is the molar Gibbs energy?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [8.507283, 17.788778] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Could you work out the molar Gibbs energy given Gibbs free energy = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [8.507283, 17.788778] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "I need the molar Gibbs energy for a Gibbs free energy of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [8.24951, 0.634021] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "If the Gibbs free energy is 8.24951 and the amount of substance is 0.634021, what is the molar Gibbs energy?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [8.24951, 0.634021] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Could you work out the molar Gibbs energy given Gibbs free energy = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [0.318734, 9.566071] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "I need the molar Gibbs energy for a Gibbs free energy of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [0.318734, 9.566071] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "If the Gibbs free energy is 0.671697 and the amount of substance is 14.2496, what is the molar Gibbs energy?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [0.671697, 14.249569] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Could you work out the molar Gibbs energy given Gibbs free energy = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [0.671697, 14.249569] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "I need the molar Gibbs energy for a Gibbs free energy of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [21.793126, 29.510609] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "If the Gibbs free energy is 21.7931 and the amount of substance is 29.5106, what is the molar Gibbs energy?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [21.793126, 29.510609] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "Could you work out the molar Gibbs energy given Gibbs free energy = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [153.149965, 18.595315] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "I need the molar Gibbs energy for a Gibbs free energy of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar Gibbs energy for [153.149965, 18.595315] (the system molar Gibbs energy (Wikidata Q88863324))" + }, + { + "q": "If the Gibbs free energy is 8.50728, what is the molar Gibbs energy?", + "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 molar Gibbs energy given Gibbs free energy = 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 molar Gibbs 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 molar Gibbs 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 molar Gibbs energy given Gibbs free energy = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Gibbs free energy: no example had one" + }, + { + "q": "What is a typical molar Gibbs 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-molar-gibbs-energy/program.py b/root/organs10/physics/specialists/solved-molar-gibbs-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0568c8bf8a1b01668c982376993596fc9751b36d --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-gibbs-energy/program.py @@ -0,0 +1,7 @@ +"""molar Gibbs energy from Gibbs free energy, amount of substance (molar Gibbs energy (Wikidata Q88863324)) +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(gibbs_free_energy, amount_of_substance): + return 1.0*gibbs_free_energy/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-gibbs-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-gibbs-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-gibbs-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-molar-heat-capacity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-heat-capacity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-heat-capacity/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-molar-heat-capacity/panel.json b/root/organs10/physics/specialists/solved-molar-heat-capacity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..943aa7f353502e4b4af2095461b3003a149ef253 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-heat-capacity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar heat capacity for heat capacity 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [107.960666, 59.4105] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [107.960666, 59.4105] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [169.526958, 280.773702] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [169.526958, 280.773702] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [1.911952, 82.240072] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [1.911952, 82.240072] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [1.643795, 252.709024] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [1.643795, 252.709024] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [18.316867, 6.838598] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [18.316867, 6.838598] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [156.50181, 185.886273] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Tell me the molar heat capacity with heat capacity of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [156.50181, 185.886273] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "What is the molar heat capacity for heat capacity 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 molar heat capacity with heat capacity 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 molar heat capacity 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 molar heat capacity 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 molar heat capacity with heat capacity 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 heat capacity: no example had one" + }, + { + "q": "Which molar heat capacity 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 heat capacity is 8.50728 and the amount of substance is 17.7888, what is the molar heat capacity?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [8.507283, 17.788778] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Could you work out the molar heat capacity given heat capacity = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [8.507283, 17.788778] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "I need the molar heat capacity for a heat capacity of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [8.24951, 0.634021] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "If the heat capacity is 8.24951 and the amount of substance is 0.634021, what is the molar heat capacity?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [8.24951, 0.634021] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Could you work out the molar heat capacity given heat capacity = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [0.318734, 9.566071] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "I need the molar heat capacity for a heat capacity of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [0.318734, 9.566071] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "If the heat capacity is 0.671697 and the amount of substance is 14.2496, what is the molar heat capacity?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [0.671697, 14.249569] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Could you work out the molar heat capacity given heat capacity = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [0.671697, 14.249569] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "I need the molar heat capacity for a heat capacity of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [21.793126, 29.510609] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "If the heat capacity is 21.7931 and the amount of substance is 29.5106, what is the molar heat capacity?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [21.793126, 29.510609] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "Could you work out the molar heat capacity given heat capacity = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [153.149965, 18.595315] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "I need the molar heat capacity for a heat capacity of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/K/mol", + "why": "molar heat capacity for [153.149965, 18.595315] (the system molar heat capacity (Wikidata Q2937190))" + }, + { + "q": "If the heat capacity is 8.50728, what is the molar heat capacity?", + "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 molar heat capacity given heat capacity = 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 molar heat capacity 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 molar heat capacity 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 molar heat capacity given heat capacity = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative heat capacity: no example had one" + }, + { + "q": "What is a typical molar heat capacity?", + "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-molar-heat-capacity/program.py b/root/organs10/physics/specialists/solved-molar-heat-capacity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3cebba796cd97606029dbcf222f99473f65414 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-heat-capacity/program.py @@ -0,0 +1,7 @@ +"""molar heat capacity from heat capacity, amount of substance (molar heat capacity (Wikidata Q2937190)) +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(heat_capacity, amount_of_substance): + return 1.0*heat_capacity/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-heat-capacity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-heat-capacity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-heat-capacity/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-molar-internal-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-internal-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-internal-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-molar-internal-energy/panel.json b/root/organs10/physics/specialists/solved-molar-internal-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..19421160f50f0571ad514b1432a2db00b6106e15 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-internal-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar internal energy for internal energy 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [107.960666, 59.4105] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [107.960666, 59.4105] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [169.526958, 280.773702] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [169.526958, 280.773702] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [1.911952, 82.240072] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [1.911952, 82.240072] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [1.643795, 252.709024] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [1.643795, 252.709024] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [18.316867, 6.838598] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [18.316867, 6.838598] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [156.50181, 185.886273] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Tell me the molar internal energy with internal energy of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [156.50181, 185.886273] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "What is the molar internal energy for internal energy 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 molar internal energy with internal energy 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 molar internal 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 molar internal 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 molar internal energy with internal energy 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 internal energy: no example had one" + }, + { + "q": "Which molar internal 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 internal energy is 8.50728 and the amount of substance is 17.7888, what is the molar internal energy?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [8.507283, 17.788778] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Could you work out the molar internal energy given internal energy = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [8.507283, 17.788778] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "I need the molar internal energy for an internal energy of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [8.24951, 0.634021] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "If the internal energy is 8.24951 and the amount of substance is 0.634021, what is the molar internal energy?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [8.24951, 0.634021] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Could you work out the molar internal energy given internal energy = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [0.318734, 9.566071] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "I need the molar internal energy for an internal energy of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [0.318734, 9.566071] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "If the internal energy is 0.671697 and the amount of substance is 14.2496, what is the molar internal energy?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [0.671697, 14.249569] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Could you work out the molar internal energy given internal energy = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [0.671697, 14.249569] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "I need the molar internal energy for an internal energy of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [21.793126, 29.510609] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "If the internal energy is 21.7931 and the amount of substance is 29.5106, what is the molar internal energy?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [21.793126, 29.510609] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "Could you work out the molar internal energy given internal energy = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [153.149965, 18.595315] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "I need the molar internal energy for an internal energy of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/mol", + "why": "molar internal energy for [153.149965, 18.595315] (the system molar internal energy (Wikidata Q88523106))" + }, + { + "q": "If the internal energy is 8.50728, what is the molar internal energy?", + "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 molar internal energy given internal energy = 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 molar internal 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 molar internal 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 molar internal energy given internal energy = -0.318734, amount of substance = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative internal energy: no example had one" + }, + { + "q": "What is a typical molar internal 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-molar-internal-energy/program.py b/root/organs10/physics/specialists/solved-molar-internal-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..2d034f6b39cf6c6bf7a56a887c3ab613a431c2c2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-internal-energy/program.py @@ -0,0 +1,7 @@ +"""molar internal energy from internal energy, amount of substance (molar internal energy (Wikidata Q88523106)) +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(internal_energy, amount_of_substance): + return 1.0*internal_energy/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-internal-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-internal-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-internal-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-molar-magnetic-susceptibility/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/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-molar-magnetic-susceptibility/panel.json b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f3b8d4385ba8b0205604c993291b74671a5c4654 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar magnetic susceptibility for molar mass 107.961, mass density 59.4105 and magnetic susceptibility 5.77717?", + "a": "10.498254293702432", + "valid": true, + "kind": "compute", + "expect": 10.498254293702432, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [107.960666, 59.4105, 5.777165] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 107.961, mass density of 59.4105 and magnetic susceptibility of 5.77717.", + "a": "10.498254293702432", + "valid": true, + "kind": "compute", + "expect": 10.498254293702432, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [107.960666, 59.4105, 5.777165] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 85.2416, mass density 160.878 and magnetic susceptibility 2.69428?", + "a": "1.4275672119863798", + "valid": true, + "kind": "compute", + "expect": 1.4275672119863798, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [85.241623, 160.878442, 2.69428] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 85.2416, mass density of 160.878 and magnetic susceptibility of 2.69428.", + "a": "1.4275672119863798", + "valid": true, + "kind": "compute", + "expect": 1.4275672119863798, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [85.241623, 160.878442, 2.69428] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 45.6157, mass density 4.97131 and magnetic susceptibility 94.305?", + "a": "865.3232325447225", + "valid": true, + "kind": "compute", + "expect": 865.3232325447225, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [45.61567, 4.971307, 94.305046] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 45.6157, mass density of 4.97131 and magnetic susceptibility of 94.305.", + "a": "865.3232325447225", + "valid": true, + "kind": "compute", + "expect": 865.3232325447225, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [45.61567, 4.971307, 94.305046] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 10.5638, mass density 198.839 and magnetic susceptibility 0.671697?", + "a": "0.03568568130708054", + "valid": true, + "kind": "compute", + "expect": 0.03568568130708054, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [10.563843, 198.838955, 0.671697] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 10.5638, mass density of 198.839 and magnetic susceptibility of 0.671697.", + "a": "0.03568568130708054", + "valid": true, + "kind": "compute", + "expect": 0.03568568130708054, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [10.563843, 198.838955, 0.671697] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 21.7931, mass density 29.5106 and magnetic susceptibility 8.50341?", + "a": "6.279634237980215", + "valid": true, + "kind": "compute", + "expect": 6.279634237980215, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [21.793126, 29.510609, 8.503407] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 21.7931, mass density of 29.5106 and magnetic susceptibility of 8.50341.", + "a": "6.279634237980215", + "valid": true, + "kind": "compute", + "expect": 6.279634237980215, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [21.793126, 29.510609, 8.503407] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 223.509, mass density 17.3414 and magnetic susceptibility 7.10705?", + "a": "91.60072422473009", + "valid": true, + "kind": "compute", + "expect": 91.60072422473009, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [223.508796, 17.341435, 7.107049] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 223.509, mass density of 17.3414 and magnetic susceptibility of 7.10705.", + "a": "91.60072422473009", + "valid": true, + "kind": "compute", + "expect": 91.60072422473009, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [223.508796, 17.341435, 7.107049] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar magnetic susceptibility for molar mass 107.961 and mass density 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Tell me the molar magnetic susceptibility with molar mass of 85.2416 and mass density of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "What is the molar magnetic susceptibility 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 molar magnetic susceptibility 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 molar magnetic susceptibility with molar mass of -45.6157, mass density of 4.97131 and magnetic susceptibility of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative molar mass: no example had one" + }, + { + "q": "Which molar magnetic susceptibility 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 molar mass is 17.7888, mass density is 167.625 and the magnetic susceptibility is 10.3291, what is the molar magnetic susceptibility?", + "a": "1.0961450581531387", + "valid": true, + "kind": "compute", + "expect": 1.0961450581531387, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [17.788778, 167.624948, 10.329054] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar magnetic susceptibility given molar mass = 17.7888, mass density = 167.625, magnetic susceptibility = 10.3291?", + "a": "1.0961450581531387", + "valid": true, + "kind": "compute", + "expect": 1.0961450581531387, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [17.788778, 167.624948, 10.329054] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar magnetic susceptibility for a molar mass of 21.511, a mass density of 173.394 and a magnetic susceptibility of 251.084, please.", + "a": "31.149197612202414", + "valid": true, + "kind": "compute", + "expect": 31.149197612202414, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [21.511016, 173.393638, 251.084037] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar mass is 21.511, mass density is 173.394 and the magnetic susceptibility is 251.084, what is the molar magnetic susceptibility?", + "a": "31.149197612202414", + "valid": true, + "kind": "compute", + "expect": 31.149197612202414, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [21.511016, 173.393638, 251.084037] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar magnetic susceptibility given molar mass = 129.245, mass density = 1.18359, magnetic susceptibility = 15.9416?", + "a": "1740.7830274187056", + "valid": true, + "kind": "compute", + "expect": 1740.7830274187056, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [129.244984, 1.18359, 15.941612] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar magnetic susceptibility for a molar mass of 129.245, a mass density of 1.18359 and a magnetic susceptibility of 15.9416, please.", + "a": "1740.7830274187056", + "valid": true, + "kind": "compute", + "expect": 1740.7830274187056, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [129.244984, 1.18359, 15.941612] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar mass is 20.3966, mass density is 18.3169 and the magnetic susceptibility is 6.8386, what is the molar magnetic susceptibility?", + "a": "7.615050191987504", + "valid": true, + "kind": "compute", + "expect": 7.615050191987504, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [20.396558, 18.316867, 6.838598] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar magnetic susceptibility given molar mass = 20.3966, mass density = 18.3169, magnetic susceptibility = 6.8386?", + "a": "7.615050191987504", + "valid": true, + "kind": "compute", + "expect": 7.615050191987504, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [20.396558, 18.316867, 6.838598] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar magnetic susceptibility for a molar mass of 185.886, a mass density of 13.2373 and a magnetic susceptibility of 4.71941, please.", + "a": "66.27285731134774", + "valid": true, + "kind": "compute", + "expect": 66.27285731134774, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [185.886273, 13.237311, 4.719415] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar mass is 185.886, mass density is 13.2373 and the magnetic susceptibility is 4.71941, what is the molar magnetic susceptibility?", + "a": "66.27285731134774", + "valid": true, + "kind": "compute", + "expect": 66.27285731134774, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [185.886273, 13.237311, 4.719415] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar magnetic susceptibility given molar mass = 9.1061, mass density = 24.5721, magnetic susceptibility = 108.451?", + "a": "40.19049097830896", + "valid": true, + "kind": "compute", + "expect": 40.19049097830896, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [9.106104, 24.572086, 108.450792] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar magnetic susceptibility for a molar mass of 9.1061, a mass density of 24.5721 and a magnetic susceptibility of 108.451, please.", + "a": "40.19049097830896", + "valid": true, + "kind": "compute", + "expect": 40.19049097830896, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar magnetic susceptibility for [9.106104, 24.572086, 108.450792] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar mass is 17.7888 and the mass density is 167.625, what is the molar magnetic susceptibility?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Could you work out the molar magnetic susceptibility given molar mass = 21.511, mass density = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Do you know the molar magnetic susceptibility 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 molar magnetic susceptibility 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 molar magnetic susceptibility given molar mass = -129.245, mass density = 1.18359, magnetic susceptibility = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative molar mass: no example had one" + }, + { + "q": "What is a typical molar magnetic susceptibility?", + "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-molar-magnetic-susceptibility/program.py b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/program.py new file mode 100644 index 0000000000000000000000000000000000000000..54d15eceff65d096755a3cf0228c81f0048fe6b7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/program.py @@ -0,0 +1,7 @@ +"""molar magnetic susceptibility from molar mass, mass density, magnetic susceptibility (molar magnetic susceptibility (Wikidata Q104438608)) +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(molar_mass, mass_density, magnetic_susceptibility): + return 1.0*magnetic_susceptibility*molar_mass/mass_density diff --git a/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-magnetic-susceptibility/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-molar-mass-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-mass-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-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-molar-mass-2/panel.json b/root/organs10/physics/specialists/solved-molar-mass-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..974e6975dda9dd2897bb0a9a6ee5d35f4dc05067 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar mass for molar magnetic susceptibility 107.961, mass density 59.4105 and magnetic susceptibility 5.77717?", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105, 5.777165] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 107.961, mass density of 59.4105 and magnetic susceptibility of 5.77717.", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105, 5.777165] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 85.2416, mass density 160.878 and magnetic susceptibility 2.69428?", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [85.241623, 160.878442, 2.69428] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 85.2416, mass density of 160.878 and magnetic susceptibility of 2.69428.", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [85.241623, 160.878442, 2.69428] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 45.6157, mass density 4.97131 and magnetic susceptibility 94.305?", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [45.61567, 4.971307, 94.305046] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 45.6157, mass density of 4.97131 and magnetic susceptibility of 94.305.", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [45.61567, 4.971307, 94.305046] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 10.5638, mass density 198.839 and magnetic susceptibility 0.671697?", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [10.563843, 198.838955, 0.671697] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 10.5638, mass density of 198.839 and magnetic susceptibility of 0.671697.", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [10.563843, 198.838955, 0.671697] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 21.7931, mass density 29.5106 and magnetic susceptibility 8.50341?", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609, 8.503407] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 21.7931, mass density of 29.5106 and magnetic susceptibility of 8.50341.", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609, 8.503407] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 223.509, mass density 17.3414 and magnetic susceptibility 7.10705?", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [223.508796, 17.341435, 7.107049] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 223.509, mass density of 17.3414 and magnetic susceptibility of 7.10705.", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [223.508796, 17.341435, 7.107049] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "What is the molar mass for molar magnetic susceptibility 107.961 and mass density 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Tell me the molar mass with molar magnetic susceptibility of 85.2416 and mass density of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "What is the molar 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 molar 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 molar mass with molar magnetic susceptibility of -45.6157, mass density of 4.97131 and magnetic susceptibility of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative molar magnetic susceptibility: no example had one" + }, + { + "q": "Which molar 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 molar magnetic susceptibility is 17.7888, mass density is 167.625 and the magnetic susceptibility is 10.3291, what is the molar mass?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [17.788778, 167.624948, 10.329054] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar mass given molar magnetic susceptibility = 17.7888, mass density = 167.625, magnetic susceptibility = 10.3291?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [17.788778, 167.624948, 10.329054] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar mass for a molar magnetic susceptibility of 21.511, a mass density of 173.394 and a magnetic susceptibility of 251.084, please.", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.511016, 173.393638, 251.084037] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar magnetic susceptibility is 21.511, mass density is 173.394 and the magnetic susceptibility is 251.084, what is the molar mass?", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.511016, 173.393638, 251.084037] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar mass given molar magnetic susceptibility = 129.245, mass density = 1.18359, magnetic susceptibility = 15.9416?", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [129.244984, 1.18359, 15.941612] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar mass for a molar magnetic susceptibility of 129.245, a mass density of 1.18359 and a magnetic susceptibility of 15.9416, please.", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [129.244984, 1.18359, 15.941612] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar magnetic susceptibility is 20.3966, mass density is 18.3169 and the magnetic susceptibility is 6.8386, what is the molar mass?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [20.396558, 18.316867, 6.838598] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar mass given molar magnetic susceptibility = 20.3966, mass density = 18.3169, magnetic susceptibility = 6.8386?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [20.396558, 18.316867, 6.838598] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar mass for a molar magnetic susceptibility of 185.886, a mass density of 13.2373 and a magnetic susceptibility of 4.71941, please.", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [185.886273, 13.237311, 4.719415] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar magnetic susceptibility is 185.886, mass density is 13.2373 and the magnetic susceptibility is 4.71941, what is the molar mass?", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [185.886273, 13.237311, 4.719415] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "Could you work out the molar mass given molar magnetic susceptibility = 9.1061, mass density = 24.5721, magnetic susceptibility = 108.451?", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [9.106104, 24.572086, 108.450792] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "I need the molar mass for a molar magnetic susceptibility of 9.1061, a mass density of 24.5721 and a magnetic susceptibility of 108.451, please.", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [9.106104, 24.572086, 108.450792] (the system molar magnetic susceptibility (Wikidata Q104438608))" + }, + { + "q": "If the molar magnetic susceptibility is 17.7888 and the mass density is 167.625, what is the molar mass?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Could you work out the molar mass given molar magnetic susceptibility = 21.511, mass density = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic susceptibility is not given" + }, + { + "q": "Do you know the molar 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 molar 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 molar mass given molar magnetic susceptibility = -129.245, mass density = 1.18359, magnetic susceptibility = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative molar magnetic susceptibility: no example had one" + }, + { + "q": "What is a typical molar 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-molar-mass-2/program.py b/root/organs10/physics/specialists/solved-molar-mass-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3f77181a965e1905408bb85d3b9171a6f0d65fae --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-2/program.py @@ -0,0 +1,7 @@ +"""molar mass from molar magnetic susceptibility, mass density, magnetic susceptibility (molar magnetic susceptibility (Wikidata Q104438608)) +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(molar_magnetic_susceptibility, mass_density, magnetic_susceptibility): + return 1.0*mass_density*molar_magnetic_susceptibility/magnetic_susceptibility diff --git a/root/organs10/physics/specialists/solved-molar-mass-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-mass-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-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-molar-mass-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-mass-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-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-molar-mass-3/panel.json b/root/organs10/physics/specialists/solved-molar-mass-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a46fdf6c167ff84f2495880c4221b726db5207e4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar mass for mass 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [169.526958, 280.773702] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [169.526958, 280.773702] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.911952, 82.240072] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.911952, 82.240072] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.643795, 252.709024] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.643795, 252.709024] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [18.316867, 6.838598] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [18.316867, 6.838598] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [156.50181, 185.886273] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Tell me the molar mass with mass of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [156.50181, 185.886273] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "What is the molar mass for mass 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 molar mass with mass 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 molar 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 molar 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 molar mass with mass 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 mass: no example had one" + }, + { + "q": "Which molar 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 mass is 8.50728 and the amount of substance is 17.7888, what is the molar mass?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.507283, 17.788778] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Could you work out the molar mass given mass = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.507283, 17.788778] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "I need the molar mass for a mass of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.24951, 0.634021] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "If the mass is 8.24951 and the amount of substance is 0.634021, what is the molar mass?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.24951, 0.634021] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Could you work out the molar mass given mass = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.318734, 9.566071] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "I need the molar mass for a mass of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.318734, 9.566071] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "If the mass is 0.671697 and the amount of substance is 14.2496, what is the molar mass?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.671697, 14.249569] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Could you work out the molar mass given mass = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.671697, 14.249569] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "I need the molar mass for a mass of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "If the mass is 21.7931 and the amount of substance is 29.5106, what is the molar mass?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "Could you work out the molar mass given mass = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [153.149965, 18.595315] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "I need the molar mass for a mass of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [153.149965, 18.595315] (the system molar mass (Wikidata Q145623))" + }, + { + "q": "If the mass is 8.50728, what is the molar mass?", + "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 molar mass given mass = 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 molar 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 molar 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 molar mass given mass = -0.318734, amount of substance = 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 molar 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-molar-mass-3/program.py b/root/organs10/physics/specialists/solved-molar-mass-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..143118cfa851ceb5240e508110d75aed9119208f --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-3/program.py @@ -0,0 +1,7 @@ +"""molar mass from mass, amount of substance (molar mass (Wikidata Q145623)) +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(mass, amount_of_substance): + return 1.0*mass/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-mass-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-mass-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass-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-molar-mass/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-mass/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-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-molar-mass/panel.json b/root/organs10/physics/specialists/solved-molar-mass/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3f4e9aff3c8606fcf2c0add7bc2c0c2cbf7ac25b --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar mass for mass 107.961 and amount 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 107.961 and amount of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [107.960666, 59.4105] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 169.527 and amount 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [169.526958, 280.773702] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 169.527 and amount of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [169.526958, 280.773702] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 1.91195 and amount 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.911952, 82.240072] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 1.91195 and amount of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.911952, 82.240072] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 1.64379 and amount 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.643795, 252.709024] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 1.64379 and amount of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [1.643795, 252.709024] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 18.3169 and amount 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [18.316867, 6.838598] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 18.3169 and amount of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [18.316867, 6.838598] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 156.502 and amount 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [156.50181, 185.886273] (the system Molar mass)" + }, + { + "q": "Tell me the molar mass with mass of 156.502 and amount of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [156.50181, 185.886273] (the system Molar mass)" + }, + { + "q": "What is the molar mass for mass 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount is not given" + }, + { + "q": "Tell me the molar mass with mass of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount is not given" + }, + { + "q": "What is the molar 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 molar 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 molar mass with mass of -1.91195 and amount 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 molar 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 mass is 8.50728 and the amount is 17.7888, what is the molar mass?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.507283, 17.788778] (the system Molar mass)" + }, + { + "q": "Could you work out the molar mass given mass = 8.50728, amount = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.507283, 17.788778] (the system Molar mass)" + }, + { + "q": "I need the molar mass for a mass of 8.24951 and an amount of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.24951, 0.634021] (the system Molar mass)" + }, + { + "q": "If the mass is 8.24951 and the amount is 0.634021, what is the molar mass?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [8.24951, 0.634021] (the system Molar mass)" + }, + { + "q": "Could you work out the molar mass given mass = 0.318734, amount = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.318734, 9.566071] (the system Molar mass)" + }, + { + "q": "I need the molar mass for a mass of 0.318734 and an amount of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.318734, 9.566071] (the system Molar mass)" + }, + { + "q": "If the mass is 0.671697 and the amount is 14.2496, what is the molar mass?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.671697, 14.249569] (the system Molar mass)" + }, + { + "q": "Could you work out the molar mass given mass = 0.671697, amount = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [0.671697, 14.249569] (the system Molar mass)" + }, + { + "q": "I need the molar mass for a mass of 21.7931 and an amount of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609] (the system Molar mass)" + }, + { + "q": "If the mass is 21.7931 and the amount is 29.5106, what is the molar mass?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [21.793126, 29.510609] (the system Molar mass)" + }, + { + "q": "Could you work out the molar mass given mass = 153.15, amount = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [153.149965, 18.595315] (the system Molar mass)" + }, + { + "q": "I need the molar mass for a mass of 153.15 and an amount of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "kg/mol", + "why": "molar mass for [153.149965, 18.595315] (the system Molar mass)" + }, + { + "q": "If the mass is 8.50728, what is the molar mass?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount is not given" + }, + { + "q": "Could you work out the molar mass given mass = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount is not given" + }, + { + "q": "Do you know the molar 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 molar 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 molar mass given mass = -0.318734, amount = 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 molar 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-molar-mass/program.py b/root/organs10/physics/specialists/solved-molar-mass/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6a9e256365452d437d7b77a96ca727aa8bf243 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-mass/program.py @@ -0,0 +1,7 @@ +"""molar mass from mass, amount (Molar mass) +The maths organ (systems.py): solved from the system m = n*M; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass, amount): + return 1.0*mass/amount diff --git a/root/organs10/physics/specialists/solved-molar-mass/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-mass/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-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-molar-optical-rotatory-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-optical-rotatory-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-molar-optical-rotatory-power/panel.json b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3ab0587024f31b1ea53ddd61ae3862689f302286 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar optical rotatory power for angle of optical rotation 107.961, cross-sectional area 59.4105 and amount of substance 5.77717?", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [107.960666, 59.4105, 5.777165] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 107.961, cross-sectional area of 59.4105 and amount of substance of 5.77717.", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [107.960666, 59.4105, 5.777165] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 85.2416, cross-sectional area 160.878 and amount of substance 2.69428?", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [85.241623, 160.878442, 2.69428] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 85.2416, cross-sectional area of 160.878 and amount of substance of 2.69428.", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [85.241623, 160.878442, 2.69428] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 45.6157, cross-sectional area 4.97131 and amount of substance 94.305?", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [45.61567, 4.971307, 94.305046] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 45.6157, cross-sectional area of 4.97131 and amount of substance of 94.305.", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [45.61567, 4.971307, 94.305046] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 10.5638, cross-sectional area 198.839 and amount of substance 0.671697?", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [10.563843, 198.838955, 0.671697] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 10.5638, cross-sectional area of 198.839 and amount of substance of 0.671697.", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [10.563843, 198.838955, 0.671697] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 21.7931, cross-sectional area 29.5106 and amount of substance 8.50341?", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [21.793126, 29.510609, 8.503407] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 21.7931, cross-sectional area of 29.5106 and amount of substance of 8.50341.", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [21.793126, 29.510609, 8.503407] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 223.509, cross-sectional area 17.3414 and amount of substance 7.10705?", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [223.508796, 17.341435, 7.107049] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 223.509, cross-sectional area of 17.3414 and amount of substance of 7.10705.", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [223.508796, 17.341435, 7.107049] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "What is the molar optical rotatory power for angle of optical rotation 107.961 and cross-sectional area 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Tell me the molar optical rotatory power with angle of optical rotation of 85.2416 and cross-sectional area of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "What is the molar optical rotatory 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 molar optical rotatory 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 molar optical rotatory power with angle of optical rotation of -45.6157, cross-sectional area of 4.97131 and amount of substance of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angle of optical rotation: no example had one" + }, + { + "q": "Which molar optical rotatory 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 angle of optical rotation is 17.7888, cross-sectional area is 167.625 and the amount of substance is 10.3291, what is the molar optical rotatory power?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [17.788778, 167.624948, 10.329054] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Could you work out the molar optical rotatory power given angle of optical rotation = 17.7888, cross-sectional area = 167.625, amount of substance = 10.3291?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [17.788778, 167.624948, 10.329054] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "I need the molar optical rotatory power for an angle of optical rotation of 21.511, a cross-sectional area of 173.394 and an amount of substance of 251.084, please.", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [21.511016, 173.393638, 251.084037] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "If the angle of optical rotation is 21.511, cross-sectional area is 173.394 and the amount of substance is 251.084, what is the molar optical rotatory power?", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [21.511016, 173.393638, 251.084037] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Could you work out the molar optical rotatory power given angle of optical rotation = 129.245, cross-sectional area = 1.18359, amount of substance = 15.9416?", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [129.244984, 1.18359, 15.941612] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "I need the molar optical rotatory power for an angle of optical rotation of 129.245, a cross-sectional area of 1.18359 and an amount of substance of 15.9416, please.", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [129.244984, 1.18359, 15.941612] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "If the angle of optical rotation is 20.3966, cross-sectional area is 18.3169 and the amount of substance is 6.8386, what is the molar optical rotatory power?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [20.396558, 18.316867, 6.838598] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Could you work out the molar optical rotatory power given angle of optical rotation = 20.3966, cross-sectional area = 18.3169, amount of substance = 6.8386?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [20.396558, 18.316867, 6.838598] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "I need the molar optical rotatory power for an angle of optical rotation of 185.886, a cross-sectional area of 13.2373 and an amount of substance of 4.71941, please.", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [185.886273, 13.237311, 4.719415] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "If the angle of optical rotation is 185.886, cross-sectional area is 13.2373 and the amount of substance is 4.71941, what is the molar optical rotatory power?", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [185.886273, 13.237311, 4.719415] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "Could you work out the molar optical rotatory power given angle of optical rotation = 9.1061, cross-sectional area = 24.5721, amount of substance = 108.451?", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [9.106104, 24.572086, 108.450792] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "I need the molar optical rotatory power for an angle of optical rotation of 9.1061, a cross-sectional area of 24.5721 and an amount of substance of 108.451, please.", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "m^2/mol", + "why": "molar optical rotatory power for [9.106104, 24.572086, 108.450792] (the system molar optical rotatory power (Wikidata Q96346994))" + }, + { + "q": "If the angle of optical rotation is 17.7888 and the cross-sectional area is 167.625, what is the molar optical rotatory power?", + "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 molar optical rotatory power given angle of optical rotation = 21.511, cross-sectional area = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Do you know the molar optical rotatory 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 molar optical rotatory 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 molar optical rotatory power given angle of optical rotation = -129.245, cross-sectional area = 1.18359, amount of substance = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angle of optical rotation: no example had one" + }, + { + "q": "What is a typical molar optical rotatory 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-molar-optical-rotatory-power/program.py b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c9a37a89e0103da6d3b9200aa74f19cbd6e789 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/program.py @@ -0,0 +1,7 @@ +"""molar optical rotatory power from angle of optical rotation, cross-sectional area, amount of substance (molar optical rotatory power (Wikidata Q96346994)) +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(angle_of_optical_rotation, cross_sectional_area, amount_of_substance): + return 1.0*angle_of_optical_rotation*cross_sectional_area/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-optical-rotatory-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-optical-rotatory-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-molar-volume/organ_formula_v2.py b/root/organs10/physics/specialists/solved-molar-volume/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-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-molar-volume/panel.json b/root/organs10/physics/specialists/solved-molar-volume/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f626b1fb9a865bc954f88041c8c0c843b4f516ac --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-volume/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the molar volume for volume 107.961 and amount of substance 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [107.960666, 59.4105] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 107.961 and amount of substance of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [107.960666, 59.4105] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 169.527 and amount of substance 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [169.526958, 280.773702] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 169.527 and amount of substance of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [169.526958, 280.773702] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 1.91195 and amount of substance 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [1.911952, 82.240072] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 1.91195 and amount of substance of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [1.911952, 82.240072] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 1.64379 and amount of substance 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [1.643795, 252.709024] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 1.64379 and amount of substance of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [1.643795, 252.709024] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 18.3169 and amount of substance 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [18.316867, 6.838598] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 18.3169 and amount of substance of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [18.316867, 6.838598] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 156.502 and amount of substance 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [156.50181, 185.886273] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Tell me the molar volume with volume of 156.502 and amount of substance of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [156.50181, 185.886273] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "What is the molar volume for volume 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 molar volume with volume 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 molar 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 molar 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 molar volume with volume 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 volume: no example had one" + }, + { + "q": "Which molar 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 is 8.50728 and the amount of substance is 17.7888, what is the molar volume?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [8.507283, 17.788778] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Could you work out the molar volume given volume = 8.50728, amount of substance = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [8.507283, 17.788778] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "I need the molar volume for a volume of 8.24951 and an amount of substance of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [8.24951, 0.634021] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "If the volume is 8.24951 and the amount of substance is 0.634021, what is the molar volume?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [8.24951, 0.634021] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Could you work out the molar volume given volume = 0.318734, amount of substance = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [0.318734, 9.566071] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "I need the molar volume for a volume of 0.318734 and an amount of substance of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [0.318734, 9.566071] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "If the volume is 0.671697 and the amount of substance is 14.2496, what is the molar volume?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [0.671697, 14.249569] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Could you work out the molar volume given volume = 0.671697, amount of substance = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [0.671697, 14.249569] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "I need the molar volume for a volume of 21.7931 and an amount of substance of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [21.793126, 29.510609] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "If the volume is 21.7931 and the amount of substance is 29.5106, what is the molar volume?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [21.793126, 29.510609] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "Could you work out the molar volume given volume = 153.15, amount of substance = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [153.149965, 18.595315] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "I need the molar volume for a volume of 153.15 and an amount of substance of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^3/mol", + "why": "molar volume for [153.149965, 18.595315] (the system molar volume (Wikidata Q487112))" + }, + { + "q": "If the volume is 8.50728, what is the molar volume?", + "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 molar volume given volume = 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 molar 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 molar 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 molar volume given volume = -0.318734, amount of substance = 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 molar 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-molar-volume/program.py b/root/organs10/physics/specialists/solved-molar-volume/program.py new file mode 100644 index 0000000000000000000000000000000000000000..e6cea0adf227e12a8a0666d406fcd5394390e0e7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-volume/program.py @@ -0,0 +1,7 @@ +"""molar volume from volume, amount of substance (molar volume (Wikidata Q487112)) +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(volume, amount_of_substance): + return 1.0*volume/amount_of_substance diff --git a/root/organs10/physics/specialists/solved-molar-volume/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-molar-volume/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-molar-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-moment-of-force-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-moment-of-force-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-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-moment-of-force-2/panel.json b/root/organs10/physics/specialists/solved-moment-of-force-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b064dd546398bd22e6578377194900c08cb242d3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the moment of force for position vector 107.961 and force 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 107.961 and force of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 169.527 and force 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 169.527 and force of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 1.91195 and force 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 1.91195 and force of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 1.64379 and force 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 1.64379 and force of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 18.3169 and force 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 18.3169 and force of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 156.502 and force 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Tell me the moment of force with position vector of 156.502 and force of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "What is the moment of force for position vector 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Tell me the moment of force with position vector of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "What is the moment of force 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 moment of force 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 moment of force with position vector of -1.91195 and force of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position vector: no example had one" + }, + { + "q": "Which moment of force 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 vector is 8.50728 and the force is 17.7888, what is the moment of force?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the moment of force given position vector = 8.50728, force = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the moment of force for a position vector of 8.24951 and a force of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the position vector is 8.24951 and the force is 0.634021, what is the moment of force?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the moment of force given position vector = 0.318734, force = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the moment of force for a position vector of 0.318734 and a force of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the position vector is 0.671697 and the force is 14.2496, what is the moment of force?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the moment of force given position vector = 0.671697, force = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the moment of force for a position vector of 21.7931 and a force of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the position vector is 21.7931 and the force is 29.5106, what is the moment of force?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "Could you work out the moment of force given position vector = 153.15, force = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "I need the moment of force for a position vector of 153.15 and a force of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system moment of force (Wikidata Q17232562))" + }, + { + "q": "If the position vector is 8.50728, what is the moment of force?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Could you work out the moment of force given position vector = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the force is not given" + }, + { + "q": "Do you know the moment of force 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 moment of force 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 moment of force given position vector = -0.318734, force = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative position vector: no example had one" + }, + { + "q": "What is a typical moment of force?", + "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-moment-of-force-2/program.py b/root/organs10/physics/specialists/solved-moment-of-force-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0b53838f893338721d3b441451c57ea9e5f893 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-2/program.py @@ -0,0 +1,7 @@ +"""moment of force from position vector, 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(position_vector, force): + return 1.0*force*position_vector diff --git a/root/organs10/physics/specialists/solved-moment-of-force-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-moment-of-force-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-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-moment-of-force-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-moment-of-force-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-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-moment-of-force-3/panel.json b/root/organs10/physics/specialists/solved-moment-of-force-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..74ffc0fb4bacbfc7c8b24b2ede1df06b0560409e --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the moment of force for angular velocity 107.961 and power 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 107.961 and power of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 169.527 and power 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 169.527 and power of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 1.91195 and power 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 1.91195 and power of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 1.64379 and power 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 1.64379 and power of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 18.3169 and power 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 18.3169 and power of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 156.502 and power 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Tell me the moment of force with angular velocity of 156.502 and power of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "What is the moment of force for angular velocity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Tell me the moment of force with angular velocity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "What is the moment of force 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 moment of force 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 moment of force with angular velocity of -1.91195 and power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular velocity: no example had one" + }, + { + "q": "Which moment of force 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 velocity is 8.50728 and the power is 17.7888, what is the moment of force?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the moment of force given angular velocity = 8.50728, power = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the moment of force for an angular velocity of 8.24951 and a power of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the angular velocity is 8.24951 and the power is 0.634021, what is the moment of force?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the moment of force given angular velocity = 0.318734, power = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the moment of force for an angular velocity of 0.318734 and a power of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the angular velocity is 0.671697 and the power is 14.2496, what is the moment of force?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the moment of force given angular velocity = 0.671697, power = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the moment of force for an angular velocity of 21.7931 and a power of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the angular velocity is 21.7931 and the power is 29.5106, what is the moment of force?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "Could you work out the moment of force given angular velocity = 153.15, power = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "I need the moment of force for an angular velocity of 153.15 and a power of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system power from torque (Wikidata Q104145185))" + }, + { + "q": "If the angular velocity is 8.50728, what is the moment of force?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Could you work out the moment of force given angular velocity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power is not given" + }, + { + "q": "Do you know the moment of force 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 moment of force 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 moment of force given angular velocity = -0.318734, power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular velocity: no example had one" + }, + { + "q": "What is a typical moment of force?", + "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-moment-of-force-3/program.py b/root/organs10/physics/specialists/solved-moment-of-force-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c032d21a988f7c39dc18e8d70f977191300d46d8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-3/program.py @@ -0,0 +1,7 @@ +"""moment of force from angular velocity, power (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(angular_velocity, power): + return 1.0*power/angular_velocity diff --git a/root/organs10/physics/specialists/solved-moment-of-force-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-moment-of-force-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force-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-moment-of-force/organ_formula_v2.py b/root/organs10/physics/specialists/solved-moment-of-force/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force/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-moment-of-force/panel.json b/root/organs10/physics/specialists/solved-moment-of-force/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..69b9887e3d31de522ef7e17ed779712ff3acf85f --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the moment of force for angular acceleration 107.961 and moment of inertia 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 107.961 and moment of inertia of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [107.960666, 59.4105] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 169.527 and moment of inertia 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 169.527 and moment of inertia of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [169.526958, 280.773702] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 1.91195 and moment of inertia 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 1.91195 and moment of inertia of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.911952, 82.240072] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 1.64379 and moment of inertia 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 1.64379 and moment of inertia of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [1.643795, 252.709024] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 18.3169 and moment of inertia 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 18.3169 and moment of inertia of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [18.316867, 6.838598] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 156.502 and moment of inertia 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of force with angular acceleration of 156.502 and moment of inertia of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [156.50181, 185.886273] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of force for angular acceleration 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the moment of inertia is not given" + }, + { + "q": "Tell me the moment of force with angular acceleration of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the moment of inertia is not given" + }, + { + "q": "What is the moment of force 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 moment of force 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 moment of force with angular acceleration of -1.91195 and moment of inertia of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular acceleration: no example had one" + }, + { + "q": "Which moment of force 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 acceleration is 8.50728 and the moment of inertia is 17.7888, what is the moment of force?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of force given angular acceleration = 8.50728, moment of inertia = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.507283, 17.788778] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of force for an angular acceleration of 8.24951 and a moment of inertia of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the angular acceleration is 8.24951 and the moment of inertia is 0.634021, what is the moment of force?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [8.24951, 0.634021] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of force given angular acceleration = 0.318734, moment of inertia = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of force for an angular acceleration of 0.318734 and a moment of inertia of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.318734, 9.566071] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the angular acceleration is 0.671697 and the moment of inertia is 14.2496, what is the moment of force?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of force given angular acceleration = 0.671697, moment of inertia = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [0.671697, 14.249569] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of force for an angular acceleration of 21.7931 and a moment of inertia of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the angular acceleration is 21.7931 and the moment of inertia is 29.5106, what is the moment of force?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [21.793126, 29.510609] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of force given angular acceleration = 153.15, moment of inertia = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of force for an angular acceleration of 153.15 and a moment of inertia of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "J", + "why": "moment of force for [153.149965, 18.595315] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the angular acceleration is 8.50728, what is the moment of force?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the moment of inertia is not given" + }, + { + "q": "Could you work out the moment of force given angular acceleration = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the moment of inertia is not given" + }, + { + "q": "Do you know the moment of force 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 moment of force 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 moment of force given angular acceleration = -0.318734, moment of inertia = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular acceleration: no example had one" + }, + { + "q": "What is a typical moment of force?", + "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-moment-of-force/program.py b/root/organs10/physics/specialists/solved-moment-of-force/program.py new file mode 100644 index 0000000000000000000000000000000000000000..02ab2a36f53c4e66516d91fbc067ff6271f0f46a --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force/program.py @@ -0,0 +1,7 @@ +"""moment of force from angular acceleration, moment of inertia (torque from angular acceleration (Wikidata Q104223516)) +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(angular_acceleration, moment_of_inertia): + return 1.0*angular_acceleration*moment_of_inertia diff --git a/root/organs10/physics/specialists/solved-moment-of-force/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-moment-of-force/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-force/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-moment-of-inertia/organ_formula_v2.py b/root/organs10/physics/specialists/solved-moment-of-inertia/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-inertia/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-moment-of-inertia/panel.json b/root/organs10/physics/specialists/solved-moment-of-inertia/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..25cd8392101f1f7e11eab0d2bc74e5128c12c10a --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-inertia/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the moment of inertia for moment of force 107.961 and angular acceleration 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [107.960666, 59.4105] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 107.961 and angular acceleration of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [107.960666, 59.4105] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 169.527 and angular acceleration 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [169.526958, 280.773702] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 169.527 and angular acceleration of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [169.526958, 280.773702] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 1.91195 and angular acceleration 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [1.911952, 82.240072] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 1.91195 and angular acceleration of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [1.911952, 82.240072] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 1.64379 and angular acceleration 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [1.643795, 252.709024] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 1.64379 and angular acceleration of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [1.643795, 252.709024] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 18.3169 and angular acceleration 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [18.316867, 6.838598] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 18.3169 and angular acceleration of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [18.316867, 6.838598] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 156.502 and angular acceleration 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [156.50181, 185.886273] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Tell me the moment of inertia with moment of force of 156.502 and angular acceleration of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [156.50181, 185.886273] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "What is the moment of inertia for moment of force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular acceleration is not given" + }, + { + "q": "Tell me the moment of inertia with moment of force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular acceleration is not given" + }, + { + "q": "What is the moment of inertia 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 moment of inertia 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 moment of inertia with moment of force of -1.91195 and angular acceleration 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 moment of inertia 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 acceleration is 17.7888, what is the moment of inertia?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [8.507283, 17.788778] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of inertia given moment of force = 8.50728, angular acceleration = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [8.507283, 17.788778] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of inertia for a moment of force of 8.24951 and an angular acceleration of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [8.24951, 0.634021] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the moment of force is 8.24951 and the angular acceleration is 0.634021, what is the moment of inertia?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [8.24951, 0.634021] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of inertia given moment of force = 0.318734, angular acceleration = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [0.318734, 9.566071] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of inertia for a moment of force of 0.318734 and an angular acceleration of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [0.318734, 9.566071] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the moment of force is 0.671697 and the angular acceleration is 14.2496, what is the moment of inertia?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [0.671697, 14.249569] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of inertia given moment of force = 0.671697, angular acceleration = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [0.671697, 14.249569] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of inertia for a moment of force of 21.7931 and an angular acceleration of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [21.793126, 29.510609] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the moment of force is 21.7931 and the angular acceleration is 29.5106, what is the moment of inertia?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [21.793126, 29.510609] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "Could you work out the moment of inertia given moment of force = 153.15, angular acceleration = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [153.149965, 18.595315] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "I need the moment of inertia for a moment of force of 153.15 and an angular acceleration of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg", + "why": "moment of inertia for [153.149965, 18.595315] (the system torque from angular acceleration (Wikidata Q104223516))" + }, + { + "q": "If the moment of force is 8.50728, what is the moment of inertia?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular acceleration is not given" + }, + { + "q": "Could you work out the moment of inertia given moment of force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular acceleration is not given" + }, + { + "q": "Do you know the moment of inertia 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 moment of inertia 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 moment of inertia given moment of force = -0.318734, angular acceleration = 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 moment of inertia?", + "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-moment-of-inertia/program.py b/root/organs10/physics/specialists/solved-moment-of-inertia/program.py new file mode 100644 index 0000000000000000000000000000000000000000..287e77bf86abd343cf8cad68eed1162955f4b6e4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-inertia/program.py @@ -0,0 +1,7 @@ +"""moment of inertia from moment of force, angular acceleration (torque from angular acceleration (Wikidata Q104223516)) +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(moment_of_force, angular_acceleration): + return 1.0*moment_of_force/angular_acceleration diff --git a/root/organs10/physics/specialists/solved-moment-of-inertia/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-moment-of-inertia/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-moment-of-inertia/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-momentum-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-momentum-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum-2/panel.json b/root/organs10/physics/specialists/solved-momentum-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..24fe59f13d58b94d711e70817a92a88072ee3d68 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the momentum for force 107.961 and time 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [107.960666, 59.4105] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 107.961 and time of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [107.960666, 59.4105] (the system Impulse)" + }, + { + "q": "What is the momentum for force 169.527 and time 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [169.526958, 280.773702] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 169.527 and time of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [169.526958, 280.773702] (the system Impulse)" + }, + { + "q": "What is the momentum for force 1.91195 and time 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.911952, 82.240072] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 1.91195 and time of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.911952, 82.240072] (the system Impulse)" + }, + { + "q": "What is the momentum for force 1.64379 and time 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.643795, 252.709024] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 1.64379 and time of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.643795, 252.709024] (the system Impulse)" + }, + { + "q": "What is the momentum for force 18.3169 and time 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [18.316867, 6.838598] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 18.3169 and time of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [18.316867, 6.838598] (the system Impulse)" + }, + { + "q": "What is the momentum for force 156.502 and time 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [156.50181, 185.886273] (the system Impulse)" + }, + { + "q": "Tell me the momentum with force of 156.502 and time of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [156.50181, 185.886273] (the system Impulse)" + }, + { + "q": "What is the momentum for force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Tell me the momentum with force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "What is the momentum 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 momentum 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 momentum with force of -1.91195 and time 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 momentum 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 time is 17.7888, what is the momentum?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.507283, 17.788778] (the system Impulse)" + }, + { + "q": "Could you work out the momentum given force = 8.50728, time = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.507283, 17.788778] (the system Impulse)" + }, + { + "q": "I need the momentum for a force of 8.24951 and a time of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.24951, 0.634021] (the system Impulse)" + }, + { + "q": "If the force is 8.24951 and the time is 0.634021, what is the momentum?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.24951, 0.634021] (the system Impulse)" + }, + { + "q": "Could you work out the momentum given force = 0.318734, time = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.318734, 9.566071] (the system Impulse)" + }, + { + "q": "I need the momentum for a force of 0.318734 and a time of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.318734, 9.566071] (the system Impulse)" + }, + { + "q": "If the force is 0.671697 and the time is 14.2496, what is the momentum?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.671697, 14.249569] (the system Impulse)" + }, + { + "q": "Could you work out the momentum given force = 0.671697, time = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.671697, 14.249569] (the system Impulse)" + }, + { + "q": "I need the momentum for a force of 21.7931 and a time of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [21.793126, 29.510609] (the system Impulse)" + }, + { + "q": "If the force is 21.7931 and the time is 29.5106, what is the momentum?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [21.793126, 29.510609] (the system Impulse)" + }, + { + "q": "Could you work out the momentum given force = 153.15, time = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [153.149965, 18.595315] (the system Impulse)" + }, + { + "q": "I need the momentum for a force of 153.15 and a time of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [153.149965, 18.595315] (the system Impulse)" + }, + { + "q": "If the force is 8.50728, what is the momentum?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Could you work out the momentum given force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the time is not given" + }, + { + "q": "Do you know the momentum 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 momentum 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 momentum given force = -0.318734, time = 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 momentum?", + "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-momentum-2/program.py b/root/organs10/physics/specialists/solved-momentum-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa7240296c690bc83442bc87eab11353ecb1c9f --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-2/program.py @@ -0,0 +1,7 @@ +"""momentum from force, time (Impulse) +The maths organ (systems.py): solved from the system p = F*t; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(force, time): + return 1.0*force*time diff --git a/root/organs10/physics/specialists/solved-momentum-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-momentum-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-momentum-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum-3/panel.json b/root/organs10/physics/specialists/solved-momentum-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..19260698ce742debb21934624032b89703265e1f --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the momentum for velocity 107.961 and mass 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [107.960666, 59.4105] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 107.961 and mass of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [107.960666, 59.4105] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 169.527 and mass 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [169.526958, 280.773702] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 169.527 and mass of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [169.526958, 280.773702] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 1.91195 and mass 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.911952, 82.240072] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 1.91195 and mass of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.911952, 82.240072] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 1.64379 and mass 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.643795, 252.709024] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 1.64379 and mass of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.643795, 252.709024] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 18.3169 and mass 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [18.316867, 6.838598] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 18.3169 and mass of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [18.316867, 6.838598] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 156.502 and mass 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [156.50181, 185.886273] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Tell me the momentum with velocity of 156.502 and mass of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [156.50181, 185.886273] (the system momentum (Wikidata Q41273))" + }, + { + "q": "What is the momentum for velocity 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass is not given" + }, + { + "q": "Tell me the momentum with velocity of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass is not given" + }, + { + "q": "What is the momentum 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 momentum 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 momentum with velocity of -1.91195 and mass of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative velocity: no example had one" + }, + { + "q": "Which momentum 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 8.50728 and the mass is 17.7888, what is the momentum?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.507283, 17.788778] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Could you work out the momentum given velocity = 8.50728, mass = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.507283, 17.788778] (the system momentum (Wikidata Q41273))" + }, + { + "q": "I need the momentum for a velocity of 8.24951 and a mass of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.24951, 0.634021] (the system momentum (Wikidata Q41273))" + }, + { + "q": "If the velocity is 8.24951 and the mass is 0.634021, what is the momentum?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.24951, 0.634021] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Could you work out the momentum given velocity = 0.318734, mass = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.318734, 9.566071] (the system momentum (Wikidata Q41273))" + }, + { + "q": "I need the momentum for a velocity of 0.318734 and a mass of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.318734, 9.566071] (the system momentum (Wikidata Q41273))" + }, + { + "q": "If the velocity is 0.671697 and the mass is 14.2496, what is the momentum?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.671697, 14.249569] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Could you work out the momentum given velocity = 0.671697, mass = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.671697, 14.249569] (the system momentum (Wikidata Q41273))" + }, + { + "q": "I need the momentum for a velocity of 21.7931 and a mass of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [21.793126, 29.510609] (the system momentum (Wikidata Q41273))" + }, + { + "q": "If the velocity is 21.7931 and the mass is 29.5106, what is the momentum?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [21.793126, 29.510609] (the system momentum (Wikidata Q41273))" + }, + { + "q": "Could you work out the momentum given velocity = 153.15, mass = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [153.149965, 18.595315] (the system momentum (Wikidata Q41273))" + }, + { + "q": "I need the momentum for a velocity of 153.15 and a mass of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [153.149965, 18.595315] (the system momentum (Wikidata Q41273))" + }, + { + "q": "If the velocity is 8.50728, what is the momentum?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass is not given" + }, + { + "q": "Could you work out the momentum given velocity = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass is not given" + }, + { + "q": "Do you know the momentum 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 momentum 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 momentum given velocity = -0.318734, mass = 9.56607?", + "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 momentum?", + "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-momentum-3/program.py b/root/organs10/physics/specialists/solved-momentum-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..210d35881172fe6797763105c451d4e35a5b5409 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-3/program.py @@ -0,0 +1,7 @@ +"""momentum from velocity, mass (momentum (Wikidata Q41273)) +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(velocity, mass): + return 1.0*mass*velocity diff --git a/root/organs10/physics/specialists/solved-momentum-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-momentum-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum-4/organ_formula_v2.py b/root/organs10/physics/specialists/solved-momentum-4/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum-4/panel.json b/root/organs10/physics/specialists/solved-momentum-4/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f271d67597debbe17d040e1d3aba517e045b6bb9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-4/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the momentum for angular momentum 107.961 and position vector 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [107.960666, 59.4105] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 107.961 and position vector of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [107.960666, 59.4105] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 169.527 and position vector 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [169.526958, 280.773702] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 169.527 and position vector of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [169.526958, 280.773702] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 1.91195 and position vector 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.911952, 82.240072] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 1.91195 and position vector of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.911952, 82.240072] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 1.64379 and position vector 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.643795, 252.709024] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 1.64379 and position vector of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [1.643795, 252.709024] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 18.3169 and position vector 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [18.316867, 6.838598] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 18.3169 and position vector of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [18.316867, 6.838598] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 156.502 and position vector 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [156.50181, 185.886273] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Tell me the momentum with angular momentum of 156.502 and position vector of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [156.50181, 185.886273] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "What is the momentum for angular momentum 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the position vector is not given" + }, + { + "q": "Tell me the momentum with angular momentum of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the position vector is not given" + }, + { + "q": "What is the momentum 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 momentum 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 momentum with angular momentum of -1.91195 and position vector 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 momentum 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 position vector is 17.7888, what is the momentum?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.507283, 17.788778] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the momentum given angular momentum = 8.50728, position vector = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.507283, 17.788778] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the momentum for an angular momentum of 8.24951 and a position vector of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.24951, 0.634021] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 8.24951 and the position vector is 0.634021, what is the momentum?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [8.24951, 0.634021] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the momentum given angular momentum = 0.318734, position vector = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.318734, 9.566071] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the momentum for an angular momentum of 0.318734 and a position vector of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.318734, 9.566071] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 0.671697 and the position vector is 14.2496, what is the momentum?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.671697, 14.249569] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the momentum given angular momentum = 0.671697, position vector = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [0.671697, 14.249569] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the momentum for an angular momentum of 21.7931 and a position vector of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [21.793126, 29.510609] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 21.7931 and the position vector is 29.5106, what is the momentum?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [21.793126, 29.510609] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "Could you work out the momentum given angular momentum = 153.15, position vector = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [153.149965, 18.595315] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "I need the momentum for an angular momentum of 153.15 and a position vector of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m*kg/s", + "why": "momentum for [153.149965, 18.595315] (the system angular momentum (Wikidata Q161254))" + }, + { + "q": "If the angular momentum is 8.50728, what is the momentum?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the position vector is not given" + }, + { + "q": "Could you work out the momentum given angular momentum = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the position vector is not given" + }, + { + "q": "Do you know the momentum 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 momentum 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 momentum given angular momentum = -0.318734, position vector = 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 momentum?", + "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-momentum-4/program.py b/root/organs10/physics/specialists/solved-momentum-4/program.py new file mode 100644 index 0000000000000000000000000000000000000000..551700d7cf8a57d10bf80136f054d19adecbc09d --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-4/program.py @@ -0,0 +1,7 @@ +"""momentum from angular momentum, position vector (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, position_vector): + return 1.0*angular_momentum/position_vector diff --git a/root/organs10/physics/specialists/solved-momentum-4/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-momentum-4/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum-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-momentum/organ_formula_v2.py b/root/organs10/physics/specialists/solved-momentum/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum/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-momentum/panel.json b/root/organs10/physics/specialists/solved-momentum/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3da860d2890c08974d2736ab23de7ba1e4a46d18 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the momentum for mass 107.961 and speed 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [107.960666, 59.4105] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 107.961 and speed of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [107.960666, 59.4105] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 169.527 and speed 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [169.526958, 280.773702] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 169.527 and speed of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [169.526958, 280.773702] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 1.91195 and speed 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.911952, 82.240072] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 1.91195 and speed of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.911952, 82.240072] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 1.64379 and speed 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.643795, 252.709024] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 1.64379 and speed of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [1.643795, 252.709024] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 18.3169 and speed 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [18.316867, 6.838598] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 18.3169 and speed of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [18.316867, 6.838598] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 156.502 and speed 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [156.50181, 185.886273] (the system Momentum)" + }, + { + "q": "Tell me the momentum with mass of 156.502 and speed of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [156.50181, 185.886273] (the system Momentum)" + }, + { + "q": "What is the momentum for mass 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Tell me the momentum with mass of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "What is the momentum 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 momentum 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 momentum with mass of -1.91195 and speed 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 momentum 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 speed is 17.7888, what is the momentum?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.507283, 17.788778] (the system Momentum)" + }, + { + "q": "Could you work out the momentum given mass = 8.50728, speed = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.507283, 17.788778] (the system Momentum)" + }, + { + "q": "I need the momentum for a mass of 8.24951 and a speed of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.24951, 0.634021] (the system Momentum)" + }, + { + "q": "If the mass is 8.24951 and the speed is 0.634021, what is the momentum?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [8.24951, 0.634021] (the system Momentum)" + }, + { + "q": "Could you work out the momentum given mass = 0.318734, speed = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.318734, 9.566071] (the system Momentum)" + }, + { + "q": "I need the momentum for a mass of 0.318734 and a speed of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.318734, 9.566071] (the system Momentum)" + }, + { + "q": "If the mass is 0.671697 and the speed is 14.2496, what is the momentum?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.671697, 14.249569] (the system Momentum)" + }, + { + "q": "Could you work out the momentum given mass = 0.671697, speed = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [0.671697, 14.249569] (the system Momentum)" + }, + { + "q": "I need the momentum for a mass of 21.7931 and a speed of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [21.793126, 29.510609] (the system Momentum)" + }, + { + "q": "If the mass is 21.7931 and the speed is 29.5106, what is the momentum?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [21.793126, 29.510609] (the system Momentum)" + }, + { + "q": "Could you work out the momentum given mass = 153.15, speed = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [153.149965, 18.595315] (the system Momentum)" + }, + { + "q": "I need the momentum for a mass of 153.15 and a speed of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "kg*m/s", + "why": "momentum for [153.149965, 18.595315] (the system Momentum)" + }, + { + "q": "If the mass is 8.50728, what is the momentum?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Could you work out the momentum given mass = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the speed is not given" + }, + { + "q": "Do you know the momentum 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 momentum 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 momentum given mass = -0.318734, speed = 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 momentum?", + "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-momentum/program.py b/root/organs10/physics/specialists/solved-momentum/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc3bce4637e251ca828d833c40074d3f5e22d1d --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum/program.py @@ -0,0 +1,7 @@ +"""momentum from mass, speed (Momentum) +The maths organ (systems.py): solved from the system p = m*v; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(mass, speed): + return 1.0*mass*speed diff --git a/root/organs10/physics/specialists/solved-momentum/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-momentum/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-momentum/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-mutual-inductance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-mutual-inductance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mutual-inductance/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-mutual-inductance/panel.json b/root/organs10/physics/specialists/solved-mutual-inductance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a1d7753d5456f8aea2b1b76a5e9cd961df4d676a --- /dev/null +++ b/root/organs10/physics/specialists/solved-mutual-inductance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the mutual inductance for total magnetic flux 107.961 and electric current 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [107.960666, 59.4105] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 107.961 and electric current of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [107.960666, 59.4105] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 169.527 and electric current 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [169.526958, 280.773702] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 169.527 and electric current of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [169.526958, 280.773702] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 1.91195 and electric current 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [1.911952, 82.240072] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 1.91195 and electric current of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [1.911952, 82.240072] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 1.64379 and electric current 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [1.643795, 252.709024] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 1.64379 and electric current of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [1.643795, 252.709024] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 18.3169 and electric current 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [18.316867, 6.838598] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 18.3169 and electric current of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [18.316867, 6.838598] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 156.502 and electric current 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [156.50181, 185.886273] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 156.502 and electric current of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [156.50181, 185.886273] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "What is the mutual inductance for total magnetic flux 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric current is not given" + }, + { + "q": "Tell me the mutual inductance with total magnetic flux of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric current is not given" + }, + { + "q": "What is the mutual inductance 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 mutual inductance 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 mutual inductance with total magnetic flux of -1.91195 and electric current of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative total magnetic flux: no example had one" + }, + { + "q": "Which mutual inductance 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 total magnetic flux is 8.50728 and the electric current is 17.7888, what is the mutual inductance?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [8.507283, 17.788778] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Could you work out the mutual inductance given total magnetic flux = 8.50728, electric current = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [8.507283, 17.788778] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "I need the mutual inductance for a total magnetic flux of 8.24951 and an electric current of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [8.24951, 0.634021] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "If the total magnetic flux is 8.24951 and the electric current is 0.634021, what is the mutual inductance?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [8.24951, 0.634021] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Could you work out the mutual inductance given total magnetic flux = 0.318734, electric current = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [0.318734, 9.566071] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "I need the mutual inductance for a total magnetic flux of 0.318734 and an electric current of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [0.318734, 9.566071] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "If the total magnetic flux is 0.671697 and the electric current is 14.2496, what is the mutual inductance?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [0.671697, 14.249569] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Could you work out the mutual inductance given total magnetic flux = 0.671697, electric current = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [0.671697, 14.249569] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "I need the mutual inductance for a total magnetic flux of 21.7931 and an electric current of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [21.793126, 29.510609] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "If the total magnetic flux is 21.7931 and the electric current is 29.5106, what is the mutual inductance?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [21.793126, 29.510609] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "Could you work out the mutual inductance given total magnetic flux = 153.15, electric current = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [153.149965, 18.595315] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "I need the mutual inductance for a total magnetic flux of 153.15 and an electric current of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "mutual inductance for [153.149965, 18.595315] (the system mutual inductance (Wikidata Q78101401))" + }, + { + "q": "If the total magnetic flux is 8.50728, what is the mutual inductance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric current is not given" + }, + { + "q": "Could you work out the mutual inductance given total magnetic flux = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric current is not given" + }, + { + "q": "Do you know the mutual inductance 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 mutual inductance 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 mutual inductance given total magnetic flux = -0.318734, electric current = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative total magnetic flux: no example had one" + }, + { + "q": "What is a typical mutual inductance?", + "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-mutual-inductance/program.py b/root/organs10/physics/specialists/solved-mutual-inductance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..807b68437ce48b6c0d2607ea43a6d9ddda6836a5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mutual-inductance/program.py @@ -0,0 +1,7 @@ +"""mutual inductance from total magnetic flux, electric current (mutual inductance (Wikidata Q78101401)) +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(total_magnetic_flux, electric_current): + return 1.0*total_magnetic_flux/electric_current diff --git a/root/organs10/physics/specialists/solved-mutual-inductance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-mutual-inductance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-mutual-inductance/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-neutron-kinetic-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-kinetic-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-neutron-kinetic-energy/panel.json b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d1906d85cd3bc025e5403852833ed71f28fe263f --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the neutron kinetic energy for reference energy 107.961 and lethargy 59.4105?", + "a": "1.704563381567068e-24", + "valid": true, + "kind": "compute", + "expect": 1.704563381567068e-24, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [107.960666, 59.4105] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 107.961 and lethargy of 59.4105.", + "a": "1.704563381567068e-24", + "valid": true, + "kind": "compute", + "expect": 1.704563381567068e-24, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [107.960666, 59.4105] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 169.527 and lethargy 280.774?", + "a": "1.9533018052524356e-120", + "valid": true, + "kind": "compute", + "expect": 1.9533018052524356e-120, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [169.526958, 280.773702] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 169.527 and lethargy of 280.774.", + "a": "1.9533018052524356e-120", + "valid": true, + "kind": "compute", + "expect": 1.9533018052524356e-120, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [169.526958, 280.773702] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 1.91195 and lethargy 82.2401?", + "a": "3.673394222328327e-36", + "valid": true, + "kind": "compute", + "expect": 3.673394222328327e-36, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [1.911952, 82.240072] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 1.91195 and lethargy of 82.2401.", + "a": "3.673394222328327e-36", + "valid": true, + "kind": "compute", + "expect": 3.673394222328327e-36, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [1.911952, 82.240072] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 1.64379 and lethargy 252.709?", + "a": "2.922220796219033e-110", + "valid": true, + "kind": "compute", + "expect": 2.922220796219033e-110, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [1.643795, 252.709024] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 1.64379 and lethargy of 252.709.", + "a": "2.922220796219033e-110", + "valid": true, + "kind": "compute", + "expect": 2.922220796219033e-110, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [1.643795, 252.709024] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 18.3169 and lethargy 6.8386?", + "a": "0.019628440259238163", + "valid": true, + "kind": "compute", + "expect": 0.019628440259238163, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [18.316867, 6.838598] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 18.3169 and lethargy of 6.8386.", + "a": "0.019628440259238163", + "valid": true, + "kind": "compute", + "expect": 0.019628440259238163, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [18.316867, 6.838598] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 156.502 and lethargy 185.886?", + "a": "2.918346324727124e-79", + "valid": true, + "kind": "compute", + "expect": 2.918346324727124e-79, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [156.50181, 185.886273] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 156.502 and lethargy of 185.886.", + "a": "2.918346324727124e-79", + "valid": true, + "kind": "compute", + "expect": 2.918346324727124e-79, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [156.50181, 185.886273] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "What is the neutron kinetic energy for reference energy 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the lethargy is not given" + }, + { + "q": "Tell me the neutron kinetic energy with reference energy of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the lethargy is not given" + }, + { + "q": "What is the neutron kinetic 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 neutron kinetic 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 neutron kinetic energy with reference energy of -1.91195 and lethargy of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reference energy: no example had one" + }, + { + "q": "Which neutron kinetic 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 reference energy is 8.50728 and the lethargy is 17.7888, what is the neutron kinetic energy?", + "a": "1.6003784026336242e-07", + "valid": true, + "kind": "compute", + "expect": 1.6003784026336242e-07, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [8.507283, 17.788778] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the neutron kinetic energy given reference energy = 8.50728, lethargy = 17.7888?", + "a": "1.6003784026336242e-07", + "valid": true, + "kind": "compute", + "expect": 1.6003784026336242e-07, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [8.507283, 17.788778] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the neutron kinetic energy for a reference energy of 8.24951 and a lethargy of 0.634021, please.", + "a": "4.375990156721791", + "valid": true, + "kind": "compute", + "expect": 4.375990156721791, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [8.24951, 0.634021] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the reference energy is 8.24951 and the lethargy is 0.634021, what is the neutron kinetic energy?", + "a": "4.375990156721791", + "valid": true, + "kind": "compute", + "expect": 4.375990156721791, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [8.24951, 0.634021] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the neutron kinetic energy given reference energy = 0.318734, lethargy = 9.56607?", + "a": "2.233246253374027e-05", + "valid": true, + "kind": "compute", + "expect": 2.233246253374027e-05, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [0.318734, 9.566071] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the neutron kinetic energy for a reference energy of 0.318734 and a lethargy of 9.56607, please.", + "a": "2.233246253374027e-05", + "valid": true, + "kind": "compute", + "expect": 2.233246253374027e-05, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [0.318734, 9.566071] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the reference energy is 0.671697 and the lethargy is 14.2496, what is the neutron kinetic energy?", + "a": "4.3517527695341915e-07", + "valid": true, + "kind": "compute", + "expect": 4.3517527695341915e-07, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [0.671697, 14.249569] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the neutron kinetic energy given reference energy = 0.671697, lethargy = 14.2496?", + "a": "4.3517527695341915e-07", + "valid": true, + "kind": "compute", + "expect": 4.3517527695341915e-07, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [0.671697, 14.249569] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the neutron kinetic energy for a reference energy of 21.7931 and a lethargy of 29.5106, please.", + "a": "3.3267873468046783e-12", + "valid": true, + "kind": "compute", + "expect": 3.3267873468046783e-12, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [21.793126, 29.510609] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the reference energy is 21.7931 and the lethargy is 29.5106, what is the neutron kinetic energy?", + "a": "3.3267873468046783e-12", + "valid": true, + "kind": "compute", + "expect": 3.3267873468046783e-12, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [21.793126, 29.510609] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "Could you work out the neutron kinetic energy given reference energy = 153.15, lethargy = 18.5953?", + "a": "1.2860978258468905e-06", + "valid": true, + "kind": "compute", + "expect": 1.2860978258468905e-06, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [153.149965, 18.595315] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "I need the neutron kinetic energy for a reference energy of 153.15 and a lethargy of 18.5953, please.", + "a": "1.2860978258468905e-06", + "valid": true, + "kind": "compute", + "expect": 1.2860978258468905e-06, + "dtype": "quantity", + "unit": "J", + "why": "neutron kinetic energy for [153.149965, 18.595315] (the system lethargy (Wikidata Q25508781))" + }, + { + "q": "If the reference energy is 8.50728, what is the neutron kinetic energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the lethargy is not given" + }, + { + "q": "Could you work out the neutron kinetic energy given reference energy = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the lethargy is not given" + }, + { + "q": "Do you know the neutron kinetic 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 neutron kinetic 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 neutron kinetic energy given reference energy = -0.318734, lethargy = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative reference energy: no example had one" + }, + { + "q": "What is a typical neutron kinetic 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-neutron-kinetic-energy/program.py b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..df269b6d2103edea292cab42f4beaf2a641ede0a --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/program.py @@ -0,0 +1,7 @@ +"""neutron kinetic energy from reference energy, lethargy (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(reference_energy, lethargy): + return 1.0*reference_energy*math.exp(-1.0*lethargy) diff --git a/root/organs10/physics/specialists/solved-neutron-kinetic-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-neutron-kinetic-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-kinetic-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-neutron-number/organ_formula_v2.py b/root/organs10/physics/specialists/solved-neutron-number/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-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-neutron-number/panel.json b/root/organs10/physics/specialists/solved-neutron-number/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6ae1812c8241e1c56a880973bc7da1e7e28e1fa4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-number/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the neutron number for hydrogen-1 mass 10.81, rest mass of atom 5.18564, mass defect 71.0225 and atomic number 2.57003?", + "a": "2.891240626167632e+28", + "valid": true, + "kind": "compute", + "expect": 2.891240626167632e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [10.809962, 5.185641, 71.022469, 2.57003] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 10.81, rest mass of atom of 5.18564, mass defect of 71.0225 and atomic number of 2.57003.", + "a": "2.891240626167632e+28", + "valid": true, + "kind": "compute", + "expect": 2.891240626167632e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [10.809962, 5.185641, 71.022469, 2.57003] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 21.7931, rest mass of atom 29.5106, mass defect 8.50341 and atomic number 0.58813?", + "a": "1.5043535768364397e+28", + "valid": true, + "kind": "compute", + "expect": 1.5043535768364397e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [21.793126, 29.510609, 8.503407, 0.58813] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 21.7931, rest mass of atom of 29.5106, mass defect of 8.50341 and atomic number of 0.58813.", + "a": "1.5043535768364397e+28", + "valid": true, + "kind": "compute", + "expect": 1.5043535768364397e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [21.793126, 29.510609, 8.503407, 0.58813] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 0.710236, rest mass of atom 1.45005, mass defect 76.5154 and atomic number 3.14491?", + "a": "4.521498751364894e+28", + "valid": true, + "kind": "compute", + "expect": 4.521498751364894e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.710236, 1.450045, 76.515411, 3.144912] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 0.710236, rest mass of atom of 1.45005, mass defect of 76.5154 and atomic number of 3.14491.", + "a": "4.521498751364894e+28", + "valid": true, + "kind": "compute", + "expect": 4.521498751364894e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.710236, 1.450045, 76.515411, 3.144912] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 0.370124, rest mass of atom 5.98214, mass defect 0.63753 and atomic number 1.90441?", + "a": "3.531377712706939e+27", + "valid": true, + "kind": "compute", + "expect": 3.531377712706939e+27, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.370124, 5.982139, 0.63753, 1.904407] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 0.370124, rest mass of atom of 5.98214, mass defect of 0.63753 and atomic number of 1.90441.", + "a": "3.531377712706939e+27", + "valid": true, + "kind": "compute", + "expect": 3.531377712706939e+27, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.370124, 5.982139, 0.63753, 1.904407] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 0.472229, rest mass of atom 33.7758, mass defect 108.711 and atomic number 3.36463?", + "a": "8.41218336587172e+28", + "valid": true, + "kind": "compute", + "expect": 8.41218336587172e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.472229, 33.775777, 108.711073, 3.364632] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 0.472229, rest mass of atom of 33.7758, mass defect of 108.711 and atomic number of 3.36463.", + "a": "8.41218336587172e+28", + "valid": true, + "kind": "compute", + "expect": 8.41218336587172e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.472229, 33.775777, 108.711073, 3.364632] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 5.53674, rest mass of atom 28.3464, mass defect 0.319575 and atomic number 1.19379?", + "a": "1.3168514000674379e+28", + "valid": true, + "kind": "compute", + "expect": 1.3168514000674379e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [5.536738, 28.346444, 0.319575, 1.193792] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 5.53674, rest mass of atom of 28.3464, mass defect of 0.319575 and atomic number of 1.19379.", + "a": "1.3168514000674379e+28", + "valid": true, + "kind": "compute", + "expect": 1.3168514000674379e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [5.536738, 28.346444, 0.319575, 1.193792] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "What is the neutron number for hydrogen-1 mass 10.81, rest mass of atom 5.18564 and mass defect 71.0225?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic number is not given" + }, + { + "q": "Tell me the neutron number with hydrogen-1 mass of 21.7931, rest mass of atom of 29.5106 and mass defect of 8.50341.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic number is not given" + }, + { + "q": "What is the neutron 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 neutron 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 neutron number with hydrogen-1 mass of -0.710236, rest mass of atom of 1.45005, mass defect of 76.5154 and atomic number of 3.14491.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative hydrogen-1 mass: no example had one" + }, + { + "q": "Which neutron 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 hydrogen-1 mass is 10.5638, rest mass of atom is 198.839, mass defect is 0.671697 and the atomic number is 14.2496, what is the neutron number?", + "a": "2.9243321356671433e+28", + "valid": true, + "kind": "compute", + "expect": 2.9243321356671433e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [10.563843, 198.838955, 0.671697, 14.249569] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Could you work out the neutron number given hydrogen-1 mass = 10.5638, rest mass of atom = 198.839, mass defect = 0.671697, atomic number = 14.2496?", + "a": "2.9243321356671433e+28", + "valid": true, + "kind": "compute", + "expect": 2.9243321356671433e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [10.563843, 198.838955, 0.671697, 14.249569] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "I need the neutron number for a hydrogen-1 mass of 13.2373, a rest mass of atom of 4.71941, a mass defect of 41.2905 and an atomic number of 2.12277, please.", + "a": "1.0693114081726253e+28", + "valid": true, + "kind": "compute", + "expect": 1.0693114081726253e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [13.237311, 4.719415, 41.290505, 2.122767] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "If the hydrogen-1 mass is 13.2373, rest mass of atom is 4.71941, mass defect is 41.2905 and the atomic number is 2.12277, what is the neutron number?", + "a": "1.0693114081726253e+28", + "valid": true, + "kind": "compute", + "expect": 1.0693114081726253e+28, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [13.237311, 4.719415, 41.290505, 2.122767] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Could you work out the neutron number given hydrogen-1 mass = 4.07774, rest mass of atom = 276.408, mass defect = 0.406608, atomic number = 0.367206?", + "a": "1.64375365403091e+29", + "valid": true, + "kind": "compute", + "expect": 1.64375365403091e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [4.077743, 276.407582, 0.406608, 0.367206] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "I need the neutron number for a hydrogen-1 mass of 4.07774, a rest mass of atom of 276.408, a mass defect of 0.406608 and an atomic number of 0.367206, please.", + "a": "1.64375365403091e+29", + "valid": true, + "kind": "compute", + "expect": 1.64375365403091e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [4.077743, 276.407582, 0.406608, 0.367206] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "If the hydrogen-1 mass is 0.634985, rest mass of atom is 291.545, mass defect is 1.25334 and the atomic number is 3.76414, what is the neutron number?", + "a": "1.7338545078669742e+29", + "valid": true, + "kind": "compute", + "expect": 1.7338545078669742e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.634985, 291.544898, 1.253336, 3.764141] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Could you work out the neutron number given hydrogen-1 mass = 0.634985, rest mass of atom = 291.545, mass defect = 1.25334, atomic number = 3.76414?", + "a": "1.7338545078669742e+29", + "valid": true, + "kind": "compute", + "expect": 1.7338545078669742e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [0.634985, 291.544898, 1.253336, 3.764141] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "I need the neutron number for a hydrogen-1 mass of 1.66108, a rest mass of atom of 228.764, a mass defect of 3.6031 and an atomic number of 2.31012, please.", + "a": "1.3644171953597921e+29", + "valid": true, + "kind": "compute", + "expect": 1.3644171953597921e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [1.661083, 228.764178, 3.603103, 2.310116] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "If the hydrogen-1 mass is 1.66108, rest mass of atom is 228.764, mass defect is 3.6031 and the atomic number is 2.31012, what is the neutron number?", + "a": "1.3644171953597921e+29", + "valid": true, + "kind": "compute", + "expect": 1.3644171953597921e+29, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [1.661083, 228.764178, 3.603103, 2.310116] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "Could you work out the neutron number given hydrogen-1 mass = 5.53629, rest mass of atom = 5.09098, mass defect = 40.3171, atomic number = 5.68433?", + "a": "8.321486725759606e+27", + "valid": true, + "kind": "compute", + "expect": 8.321486725759606e+27, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [5.536295, 5.090978, 40.317062, 5.684335] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "I need the neutron number for a hydrogen-1 mass of 5.53629, a rest mass of atom of 5.09098, a mass defect of 40.3171 and an atomic number of 5.68433, please.", + "a": "8.321486725759606e+27", + "valid": true, + "kind": "compute", + "expect": 8.321486725759606e+27, + "dtype": "quantity", + "unit": "1", + "why": "neutron number for [5.536295, 5.090978, 40.317062, 5.684335] (the system mass defect (Wikidata Q26897126))" + }, + { + "q": "If the hydrogen-1 mass is 10.5638, rest mass of atom is 198.839 and the mass defect is 0.671697, what is the neutron number?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic number is not given" + }, + { + "q": "Could you work out the neutron number given hydrogen-1 mass = 13.2373, rest mass of atom = 4.71941, mass defect = 41.2905?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the atomic number is not given" + }, + { + "q": "Do you know the neutron 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 neutron 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 neutron number given hydrogen-1 mass = -4.07774, rest mass of atom = 276.408, mass defect = 0.406608, atomic number = 0.367206?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative hydrogen-1 mass: no example had one" + }, + { + "q": "What is a typical neutron 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-neutron-number/program.py b/root/organs10/physics/specialists/solved-neutron-number/program.py new file mode 100644 index 0000000000000000000000000000000000000000..80e496155f2a892bf64945cc36613cecb1f66f5d --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-number/program.py @@ -0,0 +1,7 @@ +"""neutron number from hydrogen-1 mass, rest mass of atom, mass defect, atomic number (mass defect (Wikidata Q26897126)) +The maths organ (systems.py): solved from the system q3 = q4*q0 + q5*q1 - q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(hydrogen_1_mass, rest_mass_of_atom, mass_defect, atomic_number): + return -5.9704076813486e+26*atomic_number*hydrogen_1_mass + 5.9704076813486e+26*mass_defect + 5.9704076813486e+26*rest_mass_of_atom diff --git a/root/organs10/physics/specialists/solved-neutron-number/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-neutron-number/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-neutron-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-normal-force-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-normal-force-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force-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-normal-force-2/panel.json b/root/organs10/physics/specialists/solved-normal-force-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6c9d42283ae948fb848339e6b7e350563f103e7a --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the normal force for rolling resistance factor 107.961 and tangential force 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [107.960666, 59.4105] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 107.961 and tangential force of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [107.960666, 59.4105] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 169.527 and tangential force 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [169.526958, 280.773702] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 169.527 and tangential force of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [169.526958, 280.773702] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 1.91195 and tangential force 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.911952, 82.240072] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 1.91195 and tangential force of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.911952, 82.240072] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 1.64379 and tangential force 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.643795, 252.709024] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 1.64379 and tangential force of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.643795, 252.709024] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 18.3169 and tangential force 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [18.316867, 6.838598] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 18.3169 and tangential force of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [18.316867, 6.838598] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 156.502 and tangential force 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [156.50181, 185.886273] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 156.502 and tangential force of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [156.50181, 185.886273] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "What is the normal force for rolling resistance factor 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the tangential force is not given" + }, + { + "q": "Tell me the normal force with rolling resistance factor of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the tangential force is not given" + }, + { + "q": "What is the normal force 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 normal force 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 normal force with rolling resistance factor of -1.91195 and tangential force of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative rolling resistance factor: no example had one" + }, + { + "q": "Which normal force 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 rolling resistance factor is 8.50728 and the tangential force is 17.7888, what is the normal force?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.507283, 17.788778] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Could you work out the normal force given rolling resistance factor = 8.50728, tangential force = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.507283, 17.788778] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "I need the normal force for a rolling resistance factor of 8.24951 and a tangential force of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.24951, 0.634021] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "If the rolling resistance factor is 8.24951 and the tangential force is 0.634021, what is the normal force?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.24951, 0.634021] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Could you work out the normal force given rolling resistance factor = 0.318734, tangential force = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.318734, 9.566071] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "I need the normal force for a rolling resistance factor of 0.318734 and a tangential force of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.318734, 9.566071] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "If the rolling resistance factor is 0.671697 and the tangential force is 14.2496, what is the normal force?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.671697, 14.249569] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Could you work out the normal force given rolling resistance factor = 0.671697, tangential force = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.671697, 14.249569] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "I need the normal force for a rolling resistance factor of 21.7931 and a tangential force of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [21.793126, 29.510609] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "If the rolling resistance factor is 21.7931 and the tangential force is 29.5106, what is the normal force?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [21.793126, 29.510609] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "Could you work out the normal force given rolling resistance factor = 153.15, tangential force = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [153.149965, 18.595315] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "I need the normal force for a rolling resistance factor of 153.15 and a tangential force of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [153.149965, 18.595315] (the system rolling resistance factor (Wikidata Q91738044))" + }, + { + "q": "If the rolling resistance factor is 8.50728, what is the normal force?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the tangential force is not given" + }, + { + "q": "Could you work out the normal force given rolling resistance factor = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the tangential force is not given" + }, + { + "q": "Do you know the normal force 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 normal force 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 normal force given rolling resistance factor = -0.318734, tangential force = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative rolling resistance factor: no example had one" + }, + { + "q": "What is a typical normal force?", + "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-normal-force-2/program.py b/root/organs10/physics/specialists/solved-normal-force-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..bb22fac4b187df7235d8456b3b3b3092b6be6c6e --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force-2/program.py @@ -0,0 +1,7 @@ +"""normal force from rolling resistance factor, tangential force (rolling resistance factor (Wikidata Q91738044)) +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(rolling_resistance_factor, tangential_force): + return 1.0*tangential_force/rolling_resistance_factor diff --git a/root/organs10/physics/specialists/solved-normal-force-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-normal-force-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force-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-normal-force/organ_formula_v2.py b/root/organs10/physics/specialists/solved-normal-force/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force/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-normal-force/panel.json b/root/organs10/physics/specialists/solved-normal-force/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5fef985a017aa1bcb697af3607e5cf8f511e84bc --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the normal force for maximum tangential force 107.961 and static friction coefficient 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [107.960666, 59.4105] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 107.961 and static friction coefficient of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [107.960666, 59.4105] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 169.527 and static friction coefficient 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [169.526958, 280.773702] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 169.527 and static friction coefficient of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [169.526958, 280.773702] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 1.91195 and static friction coefficient 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.911952, 82.240072] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 1.91195 and static friction coefficient of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.911952, 82.240072] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 1.64379 and static friction coefficient 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.643795, 252.709024] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 1.64379 and static friction coefficient of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [1.643795, 252.709024] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 18.3169 and static friction coefficient 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [18.316867, 6.838598] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 18.3169 and static friction coefficient of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [18.316867, 6.838598] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 156.502 and static friction coefficient 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [156.50181, 185.886273] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Tell me the normal force with maximum tangential force of 156.502 and static friction coefficient of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [156.50181, 185.886273] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "What is the normal force for maximum tangential force 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the static friction coefficient is not given" + }, + { + "q": "Tell me the normal force with maximum tangential force of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the static friction coefficient is not given" + }, + { + "q": "What is the normal force 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 normal force 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 normal force with maximum tangential force of -1.91195 and static friction coefficient of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative maximum tangential force: no example had one" + }, + { + "q": "Which normal force 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 maximum tangential force is 8.50728 and the static friction coefficient is 17.7888, what is the normal force?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.507283, 17.788778] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Could you work out the normal force given maximum tangential force = 8.50728, static friction coefficient = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.507283, 17.788778] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "I need the normal force for a maximum tangential force of 8.24951 and a static friction coefficient of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.24951, 0.634021] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "If the maximum tangential force is 8.24951 and the static friction coefficient is 0.634021, what is the normal force?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [8.24951, 0.634021] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Could you work out the normal force given maximum tangential force = 0.318734, static friction coefficient = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.318734, 9.566071] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "I need the normal force for a maximum tangential force of 0.318734 and a static friction coefficient of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.318734, 9.566071] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "If the maximum tangential force is 0.671697 and the static friction coefficient is 14.2496, what is the normal force?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.671697, 14.249569] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Could you work out the normal force given maximum tangential force = 0.671697, static friction coefficient = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [0.671697, 14.249569] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "I need the normal force for a maximum tangential force of 21.7931 and a static friction coefficient of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [21.793126, 29.510609] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "If the maximum tangential force is 21.7931 and the static friction coefficient is 29.5106, what is the normal force?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [21.793126, 29.510609] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "Could you work out the normal force given maximum tangential force = 153.15, static friction coefficient = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [153.149965, 18.595315] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "I need the normal force for a maximum tangential force of 153.15 and a static friction coefficient of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "N", + "why": "normal force for [153.149965, 18.595315] (the system static friction coefficient (Wikidata Q73695673))" + }, + { + "q": "If the maximum tangential force is 8.50728, what is the normal force?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the static friction coefficient is not given" + }, + { + "q": "Could you work out the normal force given maximum tangential force = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the static friction coefficient is not given" + }, + { + "q": "Do you know the normal force 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 normal force 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 normal force given maximum tangential force = -0.318734, static friction coefficient = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative maximum tangential force: no example had one" + }, + { + "q": "What is a typical normal force?", + "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-normal-force/program.py b/root/organs10/physics/specialists/solved-normal-force/program.py new file mode 100644 index 0000000000000000000000000000000000000000..1680b3237520372ee8525885e000fadd61d11650 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force/program.py @@ -0,0 +1,7 @@ +"""normal force from maximum tangential force, static friction coefficient (static friction coefficient (Wikidata Q73695673)) +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(maximum_tangential_force, static_friction_coefficient): + return 1.0*maximum_tangential_force/static_friction_coefficient diff --git a/root/organs10/physics/specialists/solved-normal-force/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-normal-force/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-force/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-normal-stress/organ_formula_v2.py b/root/organs10/physics/specialists/solved-normal-stress/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-stress/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-normal-stress/panel.json b/root/organs10/physics/specialists/solved-normal-stress/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..75c8be0a82736bfd11b2d99e00d328653b1e48ee --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-stress/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the normal stress for Young's modulus 107.961 and linear strain 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [107.960666, 59.4105] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 107.961 and linear strain of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [107.960666, 59.4105] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 169.527 and linear strain 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [169.526958, 280.773702] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 169.527 and linear strain of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [169.526958, 280.773702] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 1.91195 and linear strain 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [1.911952, 82.240072] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 1.91195 and linear strain of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [1.911952, 82.240072] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 1.64379 and linear strain 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [1.643795, 252.709024] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 1.64379 and linear strain of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [1.643795, 252.709024] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 18.3169 and linear strain 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [18.316867, 6.838598] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 18.3169 and linear strain of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [18.316867, 6.838598] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 156.502 and linear strain 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [156.50181, 185.886273] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Tell me the normal stress with Young's modulus of 156.502 and linear strain of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [156.50181, 185.886273] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "What is the normal stress for Young's modulus 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear strain is not given" + }, + { + "q": "Tell me the normal stress with Young's modulus of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear strain is not given" + }, + { + "q": "What is the normal stress 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 normal stress 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 normal stress with Young's modulus of -1.91195 and linear strain of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Young's modulus: no example had one" + }, + { + "q": "Which normal stress 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 Young's modulus is 8.50728 and the linear strain is 17.7888, what is the normal stress?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [8.507283, 17.788778] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Could you work out the normal stress given Young's modulus = 8.50728, linear strain = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [8.507283, 17.788778] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "I need the normal stress for a Young's modulus of 8.24951 and a linear strain of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [8.24951, 0.634021] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "If the Young's modulus is 8.24951 and the linear strain is 0.634021, what is the normal stress?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [8.24951, 0.634021] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Could you work out the normal stress given Young's modulus = 0.318734, linear strain = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [0.318734, 9.566071] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "I need the normal stress for a Young's modulus of 0.318734 and a linear strain of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [0.318734, 9.566071] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "If the Young's modulus is 0.671697 and the linear strain is 14.2496, what is the normal stress?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [0.671697, 14.249569] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Could you work out the normal stress given Young's modulus = 0.671697, linear strain = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [0.671697, 14.249569] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "I need the normal stress for a Young's modulus of 21.7931 and a linear strain of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [21.793126, 29.510609] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "If the Young's modulus is 21.7931 and the linear strain is 29.5106, what is the normal stress?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [21.793126, 29.510609] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "Could you work out the normal stress given Young's modulus = 153.15, linear strain = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [153.149965, 18.595315] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "I need the normal stress for a Young's modulus of 153.15 and a linear strain of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "normal stress for [153.149965, 18.595315] (the system Young's modulus (Wikidata Q2091584))" + }, + { + "q": "If the Young's modulus is 8.50728, what is the normal stress?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear strain is not given" + }, + { + "q": "Could you work out the normal stress given Young's modulus = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear strain is not given" + }, + { + "q": "Do you know the normal stress 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 normal stress 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 normal stress given Young's modulus = -0.318734, linear strain = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Young's modulus: no example had one" + }, + { + "q": "What is a typical normal stress?", + "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-normal-stress/program.py b/root/organs10/physics/specialists/solved-normal-stress/program.py new file mode 100644 index 0000000000000000000000000000000000000000..9492ba853afbdda604b8a3ad88d22122d959d464 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-stress/program.py @@ -0,0 +1,7 @@ +"""normal stress from Young's modulus, linear strain (Young's modulus (Wikidata Q2091584)) +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(young_s_modulus, linear_strain): + return 1.0*linear_strain*young_s_modulus diff --git a/root/organs10/physics/specialists/solved-normal-stress/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-normal-stress/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normal-stress/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-normality/organ_formula_v2.py b/root/organs10/physics/specialists/solved-normality/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normality/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-normality/panel.json b/root/organs10/physics/specialists/solved-normality/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7d73a9f40c881a4b6008aa2a7b4021a64a275e0d --- /dev/null +++ b/root/organs10/physics/specialists/solved-normality/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the normality for valence 107.961 and amount-of-substance concentration 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [107.960666, 59.4105] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 107.961 and amount-of-substance concentration of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [107.960666, 59.4105] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 169.527 and amount-of-substance concentration 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [169.526958, 280.773702] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 169.527 and amount-of-substance concentration of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [169.526958, 280.773702] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 1.91195 and amount-of-substance concentration 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [1.911952, 82.240072] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 1.91195 and amount-of-substance concentration of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [1.911952, 82.240072] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 1.64379 and amount-of-substance concentration 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [1.643795, 252.709024] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 1.64379 and amount-of-substance concentration of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [1.643795, 252.709024] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 18.3169 and amount-of-substance concentration 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [18.316867, 6.838598] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 18.3169 and amount-of-substance concentration of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [18.316867, 6.838598] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 156.502 and amount-of-substance concentration 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [156.50181, 185.886273] (the system normality (Wikidata Q155854))" + }, + { + "q": "Tell me the normality with valence of 156.502 and amount-of-substance concentration of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [156.50181, 185.886273] (the system normality (Wikidata Q155854))" + }, + { + "q": "What is the normality for valence 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Tell me the normality with valence of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "What is the normality 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 normality 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 normality with valence of -1.91195 and amount-of-substance concentration of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative valence: no example had one" + }, + { + "q": "Which normality 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 valence is 8.50728 and the amount-of-substance concentration is 17.7888, what is the normality?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [8.507283, 17.788778] (the system normality (Wikidata Q155854))" + }, + { + "q": "Could you work out the normality given valence = 8.50728, amount-of-substance concentration = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [8.507283, 17.788778] (the system normality (Wikidata Q155854))" + }, + { + "q": "I need the normality for a valence of 8.24951 and an amount-of-substance concentration of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [8.24951, 0.634021] (the system normality (Wikidata Q155854))" + }, + { + "q": "If the valence is 8.24951 and the amount-of-substance concentration is 0.634021, what is the normality?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [8.24951, 0.634021] (the system normality (Wikidata Q155854))" + }, + { + "q": "Could you work out the normality given valence = 0.318734, amount-of-substance concentration = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [0.318734, 9.566071] (the system normality (Wikidata Q155854))" + }, + { + "q": "I need the normality for a valence of 0.318734 and an amount-of-substance concentration of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [0.318734, 9.566071] (the system normality (Wikidata Q155854))" + }, + { + "q": "If the valence is 0.671697 and the amount-of-substance concentration is 14.2496, what is the normality?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [0.671697, 14.249569] (the system normality (Wikidata Q155854))" + }, + { + "q": "Could you work out the normality given valence = 0.671697, amount-of-substance concentration = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [0.671697, 14.249569] (the system normality (Wikidata Q155854))" + }, + { + "q": "I need the normality for a valence of 21.7931 and an amount-of-substance concentration of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [21.793126, 29.510609] (the system normality (Wikidata Q155854))" + }, + { + "q": "If the valence is 21.7931 and the amount-of-substance concentration is 29.5106, what is the normality?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [21.793126, 29.510609] (the system normality (Wikidata Q155854))" + }, + { + "q": "Could you work out the normality given valence = 153.15, amount-of-substance concentration = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [153.149965, 18.595315] (the system normality (Wikidata Q155854))" + }, + { + "q": "I need the normality for a valence of 153.15 and an amount-of-substance concentration of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "mol/m^3", + "why": "normality for [153.149965, 18.595315] (the system normality (Wikidata Q155854))" + }, + { + "q": "If the valence is 8.50728, what is the normality?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Could you work out the normality given valence = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount-of-substance concentration is not given" + }, + { + "q": "Do you know the normality 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 normality 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 normality given valence = -0.318734, amount-of-substance concentration = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative valence: no example had one" + }, + { + "q": "What is a typical normality?", + "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-normality/program.py b/root/organs10/physics/specialists/solved-normality/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d8c0ee0016feedb019793ef4db048345335ea0 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normality/program.py @@ -0,0 +1,7 @@ +"""normality from valence, amount-of-substance concentration (normality (Wikidata Q155854)) +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(valence, amount_of_substance_concentration): + return 1.0*amount_of_substance_concentration*valence diff --git a/root/organs10/physics/specialists/solved-normality/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-normality/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normality/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-normalizing-function-for-meso/organ_formula_v2.py b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/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-normalizing-function-for-meso/panel.json b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d2ff3832b74acade5967572890e05f541b1cfe0d --- /dev/null +++ b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 10.81, spectral luminous efficiency for scotopic vision 5.18564, spectral luminous efficiency for photopic vision 71.0225 and adaptation coefficient for mesopic vision 2.57003?", + "a": "16.1321807426225", + "valid": true, + "kind": "compute", + "expect": 16.1321807426225, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [10.809962, 5.185641, 71.022469, 2.57003] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 10.81, spectral luminous efficiency for scotopic vision of 5.18564, spectral luminous efficiency for photopic vision of 71.0225 and adaptation coefficient for mesopic vision of 2.57003.", + "a": "16.1321807426225", + "valid": true, + "kind": "compute", + "expect": 16.1321807426225, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [10.809962, 5.185641, 71.022469, 2.57003] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 8.24951, spectral luminous efficiency for scotopic vision 0.634021, spectral luminous efficiency for photopic vision 6.34623 and adaptation coefficient for mesopic vision 21.511?", + "a": "14.97171918769871", + "valid": true, + "kind": "compute", + "expect": 14.97171918769871, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [8.24951, 0.634021, 6.346226, 21.511016] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 8.24951, spectral luminous efficiency for scotopic vision of 0.634021, spectral luminous efficiency for photopic vision of 6.34623 and adaptation coefficient for mesopic vision of 21.511.", + "a": "14.97171918769871", + "valid": true, + "kind": "compute", + "expect": 14.97171918769871, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [8.24951, 0.634021, 6.346226, 21.511016] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 0.551236, spectral luminous efficiency for scotopic vision 2.88512, spectral luminous efficiency for photopic vision 10.5638 and adaptation coefficient for mesopic vision 198.839?", + "a": "2775.063364751695", + "valid": true, + "kind": "compute", + "expect": 2775.063364751695, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [0.551236, 2.88512, 10.563843, 198.838955] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 0.551236, spectral luminous efficiency for scotopic vision of 2.88512, spectral luminous efficiency for photopic vision of 10.5638 and adaptation coefficient for mesopic vision of 198.839.", + "a": "2775.063364751695", + "valid": true, + "kind": "compute", + "expect": 2775.063364751695, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [0.551236, 2.88512, 10.563843, 198.838955] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 21.7931, spectral luminous efficiency for scotopic vision 29.5106, spectral luminous efficiency for photopic vision 8.50341 and adaptation coefficient for mesopic vision 0.58813?", + "a": "0.7872046427090239", + "valid": true, + "kind": "compute", + "expect": 0.7872046427090239, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [21.793126, 29.510609, 8.503407, 0.58813] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 21.7931, spectral luminous efficiency for scotopic vision of 29.5106, spectral luminous efficiency for photopic vision of 8.50341 and adaptation coefficient for mesopic vision of 0.58813.", + "a": "0.7872046427090239", + "valid": true, + "kind": "compute", + "expect": 0.7872046427090239, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [21.793126, 29.510609, 8.503407, 0.58813] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 7.10705, spectral luminous efficiency for scotopic vision 30.2507, spectral luminous efficiency for photopic vision 308.158 and adaptation coefficient for mesopic vision 178.166?", + "a": "6971.071645288549", + "valid": true, + "kind": "compute", + "expect": 6971.071645288549, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [7.107049, 30.250749, 308.158051, 178.165518] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 7.10705, spectral luminous efficiency for scotopic vision of 30.2507, spectral luminous efficiency for photopic vision of 308.158 and adaptation coefficient for mesopic vision of 178.166.", + "a": "6971.071645288549", + "valid": true, + "kind": "compute", + "expect": 6971.071645288549, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [7.107049, 30.250749, 308.158051, 178.165518] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 34.8151, spectral luminous efficiency for scotopic vision 0.380269, spectral luminous efficiency for photopic vision 25.4097 and adaptation coefficient for mesopic vision 20.8456?", + "a": "14.997381721988763", + "valid": true, + "kind": "compute", + "expect": 14.997381721988763, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [34.81508, 0.380269, 25.409711, 20.845641] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 34.8151, spectral luminous efficiency for scotopic vision of 0.380269, spectral luminous efficiency for photopic vision of 25.4097 and adaptation coefficient for mesopic vision of 20.8456.", + "a": "14.997381721988763", + "valid": true, + "kind": "compute", + "expect": 14.997381721988763, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [34.81508, 0.380269, 25.409711, 20.845641] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "What is the normalizing function for mesopic vision for spectral luminous efficiency for mesopic vision 10.81, spectral luminous efficiency for scotopic vision 5.18564 and spectral luminous efficiency for photopic vision 71.0225?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the adaptation coefficient for mesopic vision is not given" + }, + { + "q": "Tell me the normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of 8.24951, spectral luminous efficiency for scotopic vision of 0.634021 and spectral luminous efficiency for photopic vision of 6.34623.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the adaptation coefficient for mesopic vision is not given" + }, + { + "q": "What is the normalizing function for mesopic vision 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 normalizing function for mesopic vision 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 normalizing function for mesopic vision with spectral luminous efficiency for mesopic vision of -0.551236, spectral luminous efficiency for scotopic vision of 2.88512, spectral luminous efficiency for photopic vision of 10.5638 and adaptation coefficient for mesopic vision of 198.839.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative spectral luminous efficiency for mesopic vision: no example had one" + }, + { + "q": "Which normalizing function for mesopic vision 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 luminous efficiency for mesopic vision is 22.652, spectral luminous efficiency for scotopic vision is 1.78451, spectral luminous efficiency for photopic vision is 169.527 and the adaptation coefficient for mesopic vision is 280.774, what is the normalizing function for mesopic vision?", + "a": "2079.2603317015714", + "valid": true, + "kind": "compute", + "expect": 2079.2603317015714, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [22.652023, 1.78451, 169.526958, 280.773702] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Could you work out the normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = 22.652, spectral luminous efficiency for scotopic vision = 1.78451, spectral luminous efficiency for photopic vision = 169.527, adaptation coefficient for mesopic vision = 280.774?", + "a": "2079.2603317015714", + "valid": true, + "kind": "compute", + "expect": 2079.2603317015714, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [22.652023, 1.78451, 169.526958, 280.773702] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "I need the normalizing function for mesopic vision for a spectral luminous efficiency for mesopic vision of 13.999, a spectral luminous efficiency for scotopic vision of 0.348438, a spectral luminous efficiency for photopic vision of 45.6157 and an adaptation coefficient for mesopic vision of 4.97131, please.", + "a": "16.100100257791457", + "valid": true, + "kind": "compute", + "expect": 16.100100257791457, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [13.999029, 0.348438, 45.61567, 4.971307] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "If the spectral luminous efficiency for mesopic vision is 13.999, spectral luminous efficiency for scotopic vision is 0.348438, spectral luminous efficiency for photopic vision is 45.6157 and the adaptation coefficient for mesopic vision is 4.97131, what is the normalizing function for mesopic vision?", + "a": "16.100100257791457", + "valid": true, + "kind": "compute", + "expect": 16.100100257791457, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [13.999029, 0.348438, 45.61567, 4.971307] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Could you work out the normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = 246.329, spectral luminous efficiency for scotopic vision = 20.3966, spectral luminous efficiency for photopic vision = 18.3169, adaptation coefficient for mesopic vision = 6.8386?", + "a": "0.025065608184802652", + "valid": true, + "kind": "compute", + "expect": 0.025065608184802652, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [246.329053, 20.396558, 18.316867, 6.838598] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "I need the normalizing function for mesopic vision for a spectral luminous efficiency for mesopic vision of 246.329, a spectral luminous efficiency for scotopic vision of 20.3966, a spectral luminous efficiency for photopic vision of 18.3169 and an adaptation coefficient for mesopic vision of 6.8386, please.", + "a": "0.025065608184802652", + "valid": true, + "kind": "compute", + "expect": 0.025065608184802652, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [246.329053, 20.396558, 18.316867, 6.838598] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "If the spectral luminous efficiency for mesopic vision is 13.2373, spectral luminous efficiency for scotopic vision is 4.71941, spectral luminous efficiency for photopic vision is 41.2905 and the adaptation coefficient for mesopic vision is 2.12277, what is the normalizing function for mesopic vision?", + "a": "6.221152111314092", + "valid": true, + "kind": "compute", + "expect": 6.221152111314092, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [13.237311, 4.719415, 41.290505, 2.122767] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Could you work out the normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = 13.2373, spectral luminous efficiency for scotopic vision = 4.71941, spectral luminous efficiency for photopic vision = 41.2905, adaptation coefficient for mesopic vision = 2.12277?", + "a": "6.221152111314092", + "valid": true, + "kind": "compute", + "expect": 6.221152111314092, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [13.237311, 4.719415, 41.290505, 2.122767] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "I need the normalizing function for mesopic vision for a spectral luminous efficiency for mesopic vision of 76.5154, a spectral luminous efficiency for scotopic vision of 3.14491, a spectral luminous efficiency for photopic vision of 88.6624 and an adaptation coefficient for mesopic vision of 0.633611, please.", + "a": "0.7492567679254895", + "valid": true, + "kind": "compute", + "expect": 0.7492567679254895, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [76.515411, 3.144912, 88.662361, 0.633611] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "If the spectral luminous efficiency for mesopic vision is 76.5154, spectral luminous efficiency for scotopic vision is 3.14491, spectral luminous efficiency for photopic vision is 88.6624 and the adaptation coefficient for mesopic vision is 0.633611, what is the normalizing function for mesopic vision?", + "a": "0.7492567679254895", + "valid": true, + "kind": "compute", + "expect": 0.7492567679254895, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [76.515411, 3.144912, 88.662361, 0.633611] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "Could you work out the normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = 241.598, spectral luminous efficiency for scotopic vision = 1.13479, spectral luminous efficiency for photopic vision = 0.744193, adaptation coefficient for mesopic vision = 1.35435?", + "a": "0.0025074107745071453", + "valid": true, + "kind": "compute", + "expect": 0.0025074107745071453, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [241.598281, 1.134791, 0.744193, 1.354346] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "I need the normalizing function for mesopic vision for a spectral luminous efficiency for mesopic vision of 241.598, a spectral luminous efficiency for scotopic vision of 1.13479, a spectral luminous efficiency for photopic vision of 0.744193 and an adaptation coefficient for mesopic vision of 1.35435, please.", + "a": "0.0025074107745071453", + "valid": true, + "kind": "compute", + "expect": 0.0025074107745071453, + "dtype": "quantity", + "unit": "1", + "why": "normalizing function for mesopic vision for [241.598281, 1.134791, 0.744193, 1.354346] (the system spectral luminous efficiency for mesopic vision (Wikidata Q107018545))" + }, + { + "q": "If the spectral luminous efficiency for mesopic vision is 22.652, spectral luminous efficiency for scotopic vision is 1.78451 and the spectral luminous efficiency for photopic vision is 169.527, what is the normalizing function for mesopic vision?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the adaptation coefficient for mesopic vision is not given" + }, + { + "q": "Could you work out the normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = 13.999, spectral luminous efficiency for scotopic vision = 0.348438, spectral luminous efficiency for photopic vision = 45.6157?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the adaptation coefficient for mesopic vision is not given" + }, + { + "q": "Do you know the normalizing function for mesopic vision 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 normalizing function for mesopic vision 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 normalizing function for mesopic vision given spectral luminous efficiency for mesopic vision = -246.329, spectral luminous efficiency for scotopic vision = 20.3966, spectral luminous efficiency for photopic vision = 18.3169, adaptation coefficient for mesopic vision = 6.8386?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative spectral luminous efficiency for mesopic vision: no example had one" + }, + { + "q": "What is a typical normalizing function for mesopic vision?", + "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-normalizing-function-for-meso/program.py b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/program.py new file mode 100644 index 0000000000000000000000000000000000000000..573108714ddc0461deabed0124a226b67dac7d86 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/program.py @@ -0,0 +1,7 @@ +"""normalizing function for mesopic vision from spectral luminous efficiency for mesopic vision, spectral luminous efficiency for scotopic vision, spectral luminous efficiency for photopic vision, adaptation coefficient for mesopic vision (spectral luminous efficiency for mesopic vision (Wikidata Q107018545)) +The maths organ (systems.py): solved from the system q0 = ((1)/(q3))*( q4*q2 + ( 1 - q4 )*q1 ); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(spectral_luminous_efficiency_for_mesopic_vision, spectral_luminous_efficiency_for_scotopic_vision, spectral_luminous_efficiency_for_photopic_vision, adaptation_coefficient_for_mesopic_vision): + return (1.0*adaptation_coefficient_for_mesopic_vision*spectral_luminous_efficiency_for_photopic_vision - 1.0*adaptation_coefficient_for_mesopic_vision*spectral_luminous_efficiency_for_scotopic_vision + 1.0*spectral_luminous_efficiency_for_scotopic_vision)/spectral_luminous_efficiency_for_mesopic_vision diff --git a/root/organs10/physics/specialists/solved-normalizing-function-for-meso/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-normalizing-function-for-meso/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-nuclear-g-factor/organ_formula_v2.py b/root/organs10/physics/specialists/solved-nuclear-g-factor/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-nuclear-g-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-nuclear-g-factor/panel.json b/root/organs10/physics/specialists/solved-nuclear-g-factor/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d217bfaa19787d6e7dc8b85689a15cd0c789ffec --- /dev/null +++ b/root/organs10/physics/specialists/solved-nuclear-g-factor/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the nuclear g factor for magnetic dipole moment 107.961 and nuclear spin quantum number 59.4105?", + "a": "3.5978543297134544e+26", + "valid": true, + "kind": "compute", + "expect": 3.5978543297134544e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [107.960666, 59.4105] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 107.961 and nuclear spin quantum number of 59.4105.", + "a": "3.5978543297134544e+26", + "valid": true, + "kind": "compute", + "expect": 3.5978543297134544e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [107.960666, 59.4105] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 169.527 and nuclear spin quantum number 280.774?", + "a": "1.1954284011420639e+26", + "valid": true, + "kind": "compute", + "expect": 1.1954284011420639e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [169.526958, 280.773702] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 169.527 and nuclear spin quantum number of 280.774.", + "a": "1.1954284011420639e+26", + "valid": true, + "kind": "compute", + "expect": 1.1954284011420639e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [169.526958, 280.773702] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 1.91195 and nuclear spin quantum number 82.2401?", + "a": "4.6029332820558894e+24", + "valid": true, + "kind": "compute", + "expect": 4.6029332820558894e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [1.911952, 82.240072] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 1.91195 and nuclear spin quantum number of 82.2401.", + "a": "4.6029332820558894e+24", + "valid": true, + "kind": "compute", + "expect": 4.6029332820558894e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [1.911952, 82.240072] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 1.64379 and nuclear spin quantum number 252.709?", + "a": "1.2878588443572066e+24", + "valid": true, + "kind": "compute", + "expect": 1.2878588443572066e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [1.643795, 252.709024] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 1.64379 and nuclear spin quantum number of 252.709.", + "a": "1.2878588443572066e+24", + "valid": true, + "kind": "compute", + "expect": 1.2878588443572066e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [1.643795, 252.709024] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 18.3169 and nuclear spin quantum number 6.8386?", + "a": "5.3030453801151726e+26", + "valid": true, + "kind": "compute", + "expect": 5.3030453801151726e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [18.316867, 6.838598] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 18.3169 and nuclear spin quantum number of 6.8386.", + "a": "5.3030453801151726e+26", + "valid": true, + "kind": "compute", + "expect": 5.3030453801151726e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [18.316867, 6.838598] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 156.502 and nuclear spin quantum number 185.886?", + "a": "1.6669143083237792e+26", + "valid": true, + "kind": "compute", + "expect": 1.6669143083237792e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [156.50181, 185.886273] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 156.502 and nuclear spin quantum number of 185.886.", + "a": "1.6669143083237792e+26", + "valid": true, + "kind": "compute", + "expect": 1.6669143083237792e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [156.50181, 185.886273] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "What is the nuclear g factor for magnetic dipole moment 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the nuclear spin quantum number is not given" + }, + { + "q": "Tell me the nuclear g factor with magnetic dipole moment of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the nuclear spin quantum number is not given" + }, + { + "q": "What is the nuclear g 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 nuclear g 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 nuclear g factor with magnetic dipole moment of -1.91195 and nuclear spin quantum number of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic dipole moment: no example had one" + }, + { + "q": "Which nuclear g 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 magnetic dipole moment is 8.50728 and the nuclear spin quantum number is 17.7888, what is the nuclear g factor?", + "a": "9.468604441762147e+25", + "valid": true, + "kind": "compute", + "expect": 9.468604441762147e+25, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [8.507283, 17.788778] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Could you work out the nuclear g factor given magnetic dipole moment = 8.50728, nuclear spin quantum number = 17.7888?", + "a": "9.468604441762147e+25", + "valid": true, + "kind": "compute", + "expect": 9.468604441762147e+25, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [8.507283, 17.788778] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "I need the nuclear g factor for a magnetic dipole moment of 8.24951 and a nuclear spin quantum number of 0.634021, please.", + "a": "2.576117999106748e+27", + "valid": true, + "kind": "compute", + "expect": 2.576117999106748e+27, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [8.24951, 0.634021] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "If the magnetic dipole moment is 8.24951 and the nuclear spin quantum number is 0.634021, what is the nuclear g factor?", + "a": "2.576117999106748e+27", + "valid": true, + "kind": "compute", + "expect": 2.576117999106748e+27, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [8.24951, 0.634021] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Could you work out the nuclear g factor given magnetic dipole moment = 0.318734, nuclear spin quantum number = 9.56607?", + "a": "6.596842089905492e+24", + "valid": true, + "kind": "compute", + "expect": 6.596842089905492e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [0.318734, 9.566071] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "I need the nuclear g factor for a magnetic dipole moment of 0.318734 and a nuclear spin quantum number of 9.56607, please.", + "a": "6.596842089905492e+24", + "valid": true, + "kind": "compute", + "expect": 6.596842089905492e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [0.318734, 9.566071] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "If the magnetic dipole moment is 0.671697 and the nuclear spin quantum number is 14.2496, what is the nuclear g factor?", + "a": "9.332823000063392e+24", + "valid": true, + "kind": "compute", + "expect": 9.332823000063392e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [0.671697, 14.249569] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Could you work out the nuclear g factor given magnetic dipole moment = 0.671697, nuclear spin quantum number = 14.2496?", + "a": "9.332823000063392e+24", + "valid": true, + "kind": "compute", + "expect": 9.332823000063392e+24, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [0.671697, 14.249569] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "I need the nuclear g factor for a magnetic dipole moment of 21.7931 and a nuclear spin quantum number of 29.5106, please.", + "a": "1.4621186019120284e+26", + "valid": true, + "kind": "compute", + "expect": 1.4621186019120284e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [21.793126, 29.510609] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "If the magnetic dipole moment is 21.7931 and the nuclear spin quantum number is 29.5106, what is the nuclear g factor?", + "a": "1.4621186019120284e+26", + "valid": true, + "kind": "compute", + "expect": 1.4621186019120284e+26, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [21.793126, 29.510609] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "Could you work out the nuclear g factor given magnetic dipole moment = 153.15, nuclear spin quantum number = 18.5953?", + "a": "1.630626821364366e+27", + "valid": true, + "kind": "compute", + "expect": 1.630626821364366e+27, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [153.149965, 18.595315] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "I need the nuclear g factor for a magnetic dipole moment of 153.15 and a nuclear spin quantum number of 18.5953, please.", + "a": "1.630626821364366e+27", + "valid": true, + "kind": "compute", + "expect": 1.630626821364366e+27, + "dtype": "quantity", + "unit": "1", + "why": "nuclear g factor for [153.149965, 18.595315] (the system nuclear g factor (Wikidata Q97591250))" + }, + { + "q": "If the magnetic dipole moment is 8.50728, what is the nuclear g factor?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the nuclear spin quantum number is not given" + }, + { + "q": "Could you work out the nuclear g factor given magnetic dipole moment = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the nuclear spin quantum number is not given" + }, + { + "q": "Do you know the nuclear g 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 nuclear g 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 nuclear g factor given magnetic dipole moment = -0.318734, nuclear spin quantum number = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic dipole moment: no example had one" + }, + { + "q": "What is a typical nuclear g 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-nuclear-g-factor/program.py b/root/organs10/physics/specialists/solved-nuclear-g-factor/program.py new file mode 100644 index 0000000000000000000000000000000000000000..6a333540251dbf1eb10888225397cb5f534f7b05 --- /dev/null +++ b/root/organs10/physics/specialists/solved-nuclear-g-factor/program.py @@ -0,0 +1,7 @@ +"""nuclear g factor from magnetic dipole moment, nuclear spin quantum number (nuclear g factor (Wikidata Q97591250)) +The maths organ (systems.py): solved from the system q1 = ((q2)/(q3*q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(magnetic_dipole_moment, nuclear_spin_quantum_number): + return 1.97989076467082e+26*magnetic_dipole_moment/nuclear_spin_quantum_number diff --git a/root/organs10/physics/specialists/solved-nuclear-g-factor/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-nuclear-g-factor/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-nuclear-g-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-number-density-of-atoms-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms-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-number-density-of-atoms-2/panel.json b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..30cc1f7be31484ccdad0f5ab93d93e84da71badb --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number density of atoms for atomic attenuation coefficient 107.961 and linear attenuation coefficient 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [107.960666, 59.4105] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 107.961 and linear attenuation coefficient of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [107.960666, 59.4105] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 169.527 and linear attenuation coefficient 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [169.526958, 280.773702] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 169.527 and linear attenuation coefficient of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [169.526958, 280.773702] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 1.91195 and linear attenuation coefficient 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.911952, 82.240072] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 1.91195 and linear attenuation coefficient of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.911952, 82.240072] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 1.64379 and linear attenuation coefficient 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.643795, 252.709024] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 1.64379 and linear attenuation coefficient of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.643795, 252.709024] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 18.3169 and linear attenuation coefficient 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [18.316867, 6.838598] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 18.3169 and linear attenuation coefficient of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [18.316867, 6.838598] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 156.502 and linear attenuation coefficient 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [156.50181, 185.886273] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 156.502 and linear attenuation coefficient of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [156.50181, 185.886273] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "What is the number density of atoms for atomic attenuation coefficient 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear attenuation coefficient is not given" + }, + { + "q": "Tell me the number density of atoms with atomic attenuation coefficient of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear attenuation coefficient is not given" + }, + { + "q": "What is the number density of atoms 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 number density of atoms 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 number density of atoms with atomic attenuation coefficient of -1.91195 and linear attenuation coefficient of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative atomic attenuation coefficient: no example had one" + }, + { + "q": "Which number density of atoms 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 atomic attenuation coefficient is 8.50728 and the linear attenuation coefficient is 17.7888, what is the number density of atoms?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.507283, 17.788778] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Could you work out the number density of atoms given atomic attenuation coefficient = 8.50728, linear attenuation coefficient = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.507283, 17.788778] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "I need the number density of atoms for an atomic attenuation coefficient of 8.24951 and a linear attenuation coefficient of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.24951, 0.634021] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "If the atomic attenuation coefficient is 8.24951 and the linear attenuation coefficient is 0.634021, what is the number density of atoms?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.24951, 0.634021] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Could you work out the number density of atoms given atomic attenuation coefficient = 0.318734, linear attenuation coefficient = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.318734, 9.566071] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "I need the number density of atoms for an atomic attenuation coefficient of 0.318734 and a linear attenuation coefficient of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.318734, 9.566071] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "If the atomic attenuation coefficient is 0.671697 and the linear attenuation coefficient is 14.2496, what is the number density of atoms?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.671697, 14.249569] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Could you work out the number density of atoms given atomic attenuation coefficient = 0.671697, linear attenuation coefficient = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.671697, 14.249569] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "I need the number density of atoms for an atomic attenuation coefficient of 21.7931 and a linear attenuation coefficient of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [21.793126, 29.510609] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "If the atomic attenuation coefficient is 21.7931 and the linear attenuation coefficient is 29.5106, what is the number density of atoms?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [21.793126, 29.510609] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "Could you work out the number density of atoms given atomic attenuation coefficient = 153.15, linear attenuation coefficient = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [153.149965, 18.595315] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "I need the number density of atoms for an atomic attenuation coefficient of 153.15 and a linear attenuation coefficient of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [153.149965, 18.595315] (the system atomic attenuation coefficient (Wikidata Q98592911))" + }, + { + "q": "If the atomic attenuation coefficient is 8.50728, what is the number density of atoms?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear attenuation coefficient is not given" + }, + { + "q": "Could you work out the number density of atoms given atomic attenuation coefficient = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear attenuation coefficient is not given" + }, + { + "q": "Do you know the number density of atoms 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 number density of atoms 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 number density of atoms given atomic attenuation coefficient = -0.318734, linear attenuation coefficient = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative atomic attenuation coefficient: no example had one" + }, + { + "q": "What is a typical number density of atoms?", + "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-number-density-of-atoms-2/program.py b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..07541532148f7f17211796c38c25dec82a4c44ca --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/program.py @@ -0,0 +1,7 @@ +"""number density of atoms from atomic attenuation coefficient, linear attenuation coefficient (atomic attenuation coefficient (Wikidata Q98592911)) +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(atomic_attenuation_coefficient, linear_attenuation_coefficient): + return 1.0*linear_attenuation_coefficient/atomic_attenuation_coefficient diff --git a/root/organs10/physics/specialists/solved-number-density-of-atoms-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-density-of-atoms-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms-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-number-density-of-atoms/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-density-of-atoms/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms/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-number-density-of-atoms/panel.json b/root/organs10/physics/specialists/solved-number-density-of-atoms/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..172c24545af378e22cbbfb463e50ac608134b7a7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number density of atoms for total atomic stopping power 107.961 and linear stopping power 59.4105?", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [107.960666, 59.4105] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 107.961 and linear stopping power of 59.4105.", + "a": "0.5502976449934551", + "valid": true, + "kind": "compute", + "expect": 0.5502976449934551, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [107.960666, 59.4105] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 169.527 and linear stopping power 280.774?", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [169.526958, 280.773702] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 169.527 and linear stopping power of 280.774.", + "a": "1.656218609813279", + "valid": true, + "kind": "compute", + "expect": 1.656218609813279, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [169.526958, 280.773702] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 1.91195 and linear stopping power 82.2401?", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.911952, 82.240072] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 1.91195 and linear stopping power of 82.2401.", + "a": "43.01367504910926", + "valid": true, + "kind": "compute", + "expect": 43.01367504910926, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.911952, 82.240072] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 1.64379 and linear stopping power 252.709?", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.643795, 252.709024] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 1.64379 and linear stopping power of 252.709.", + "a": "153.73507534197344", + "valid": true, + "kind": "compute", + "expect": 153.73507534197344, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [1.643795, 252.709024] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 18.3169 and linear stopping power 6.8386?", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [18.316867, 6.838598] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 18.3169 and linear stopping power of 6.8386.", + "a": "0.37334976843585305", + "valid": true, + "kind": "compute", + "expect": 0.37334976843585305, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [18.316867, 6.838598] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 156.502 and linear stopping power 185.886?", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [156.50181, 185.886273] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 156.502 and linear stopping power of 185.886.", + "a": "1.187757975790468", + "valid": true, + "kind": "compute", + "expect": 1.187757975790468, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [156.50181, 185.886273] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "What is the number density of atoms for total atomic stopping power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear stopping power is not given" + }, + { + "q": "Tell me the number density of atoms with total atomic stopping power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear stopping power is not given" + }, + { + "q": "What is the number density of atoms 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 number density of atoms 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 number density of atoms with total atomic stopping power of -1.91195 and linear stopping power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative total atomic stopping power: no example had one" + }, + { + "q": "Which number density of atoms 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 total atomic stopping power is 8.50728 and the linear stopping power is 17.7888, what is the number density of atoms?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.507283, 17.788778] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Could you work out the number density of atoms given total atomic stopping power = 8.50728, linear stopping power = 17.7888?", + "a": "2.0910058888280627", + "valid": true, + "kind": "compute", + "expect": 2.0910058888280627, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.507283, 17.788778] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "I need the number density of atoms for a total atomic stopping power of 8.24951 and a linear stopping power of 0.634021, please.", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.24951, 0.634021] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "If the total atomic stopping power is 8.24951 and the linear stopping power is 0.634021, what is the number density of atoms?", + "a": "0.07685559300301205", + "valid": true, + "kind": "compute", + "expect": 0.07685559300301205, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [8.24951, 0.634021] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Could you work out the number density of atoms given total atomic stopping power = 0.318734, linear stopping power = 9.56607?", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.318734, 9.566071] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "I need the number density of atoms for a total atomic stopping power of 0.318734 and a linear stopping power of 9.56607, please.", + "a": "30.01270513508963", + "valid": true, + "kind": "compute", + "expect": 30.01270513508963, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.318734, 9.566071] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "If the total atomic stopping power is 0.671697 and the linear stopping power is 14.2496, what is the number density of atoms?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.671697, 14.249569] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Could you work out the number density of atoms given total atomic stopping power = 0.671697, linear stopping power = 14.2496?", + "a": "21.214275301882097", + "valid": true, + "kind": "compute", + "expect": 21.214275301882097, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [0.671697, 14.249569] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "I need the number density of atoms for a total atomic stopping power of 21.7931 and a linear stopping power of 29.5106, please.", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [21.793126, 29.510609] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "If the total atomic stopping power is 21.7931 and the linear stopping power is 29.5106, what is the number density of atoms?", + "a": "1.3541245984297685", + "valid": true, + "kind": "compute", + "expect": 1.3541245984297685, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [21.793126, 29.510609] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "Could you work out the number density of atoms given total atomic stopping power = 153.15, linear stopping power = 18.5953?", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [153.149965, 18.595315] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "I need the number density of atoms for a total atomic stopping power of 153.15 and a linear stopping power of 18.5953, please.", + "a": "0.12141899904566884", + "valid": true, + "kind": "compute", + "expect": 0.12141899904566884, + "dtype": "quantity", + "unit": "1/m^3", + "why": "number density of atoms for [153.149965, 18.595315] (the system total atomic stopping power (Wikidata Q112725871))" + }, + { + "q": "If the total atomic stopping power is 8.50728, what is the number density of atoms?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear stopping power is not given" + }, + { + "q": "Could you work out the number density of atoms given total atomic stopping power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the linear stopping power is not given" + }, + { + "q": "Do you know the number density of atoms 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 number density of atoms 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 number density of atoms given total atomic stopping power = -0.318734, linear stopping power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative total atomic stopping power: no example had one" + }, + { + "q": "What is a typical number density of atoms?", + "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-number-density-of-atoms/program.py b/root/organs10/physics/specialists/solved-number-density-of-atoms/program.py new file mode 100644 index 0000000000000000000000000000000000000000..ba06f6805282631aa5b96a75c68476fd3ff1f336 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms/program.py @@ -0,0 +1,7 @@ +"""number density of atoms from total atomic stopping power, linear stopping power (total atomic stopping power (Wikidata Q112725871)) +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(total_atomic_stopping_power, linear_stopping_power): + return 1.0*linear_stopping_power/total_atomic_stopping_power diff --git a/root/organs10/physics/specialists/solved-number-density-of-atoms/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-density-of-atoms/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-density-of-atoms/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-number-of-antiquarks/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-antiquarks/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-antiquarks/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-number-of-antiquarks/panel.json b/root/organs10/physics/specialists/solved-number-of-antiquarks/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3301ce8163f45ac5cb5c3aa807bffc69d4281042 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-antiquarks/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of antiquarks for number of quarks 5.77717 and baryon number 1.89126?", + "a": "0.10339750210871124", + "valid": true, + "kind": "compute", + "expect": 0.10339750210871124, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [5.777165, 1.891256] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 5.77717 and baryon number of 1.89126.", + "a": "0.10339750210871124", + "valid": true, + "kind": "compute", + "expect": 0.10339750210871124, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [5.777165, 1.891256] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 157.223 and baryon number 35.6412?", + "a": "50.299088696720986", + "valid": true, + "kind": "compute", + "expect": 50.299088696720986, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [157.22256, 35.641157] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 157.223 and baryon number of 35.6412.", + "a": "50.299088696720986", + "valid": true, + "kind": "compute", + "expect": 50.299088696720986, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [157.22256, 35.641157] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 126.709 and baryon number 1.70503?", + "a": "121.59415466445998", + "valid": true, + "kind": "compute", + "expect": 121.59415466445998, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [126.709252, 1.705032] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 126.709 and baryon number of 1.70503.", + "a": "121.59415466445998", + "valid": true, + "kind": "compute", + "expect": 121.59415466445998, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [126.709252, 1.705032] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 41.6566 and baryon number 13.8779?", + "a": "0.023037043472079688", + "valid": true, + "kind": "compute", + "expect": 0.023037043472079688, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [41.656639, 13.877867] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 41.6566 and baryon number of 13.8779.", + "a": "0.023037043472079688", + "valid": true, + "kind": "compute", + "expect": 0.023037043472079688, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [41.656639, 13.877867] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 8.50341 and baryon number 0.58813?", + "a": "6.739018203872142", + "valid": true, + "kind": "compute", + "expect": 6.739018203872142, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [8.503407, 0.58813] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 8.50341 and baryon number of 0.58813.", + "a": "6.739018203872142", + "valid": true, + "kind": "compute", + "expect": 6.739018203872142, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [8.503407, 0.58813] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 75.8534 and baryon number 0.558623?", + "a": "74.17756540160018", + "valid": true, + "kind": "compute", + "expect": 74.17756540160018, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [75.853435, 0.558623] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 75.8534 and baryon number of 0.558623.", + "a": "74.17756540160018", + "valid": true, + "kind": "compute", + "expect": 74.17756540160018, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [75.853435, 0.558623] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of antiquarks for number of quarks 5.77717?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Tell me the number of antiquarks with number of quarks of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "What is the number of antiquarks 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 number of antiquarks 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 number of antiquarks with number of quarks of -126.709 and baryon number of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of quarks: no example had one" + }, + { + "q": "Which number of antiquarks 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 number of quarks is 167.625 and the baryon number is 10.3291, what is the number of antiquarks?", + "a": "136.6377843939411", + "valid": true, + "kind": "compute", + "expect": 136.6377843939411, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [167.624948, 10.329054] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of antiquarks given number of quarks = 167.625, baryon number = 10.3291?", + "a": "136.6377843939411", + "valid": true, + "kind": "compute", + "expect": 136.6377843939411, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [167.624948, 10.329054] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of antiquarks for a number of quarks of 13.999 and a baryon number of 0.348438, please.", + "a": "12.953715936233845", + "valid": true, + "kind": "compute", + "expect": 12.953715936233845, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [13.999029, 0.348438] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of quarks is 13.999 and the baryon number is 0.348438, what is the number of antiquarks?", + "a": "12.953715936233845", + "valid": true, + "kind": "compute", + "expect": 12.953715936233845, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [13.999029, 0.348438] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of antiquarks given number of quarks = 81.1967, baryon number = 6.98086?", + "a": "60.254135718484626", + "valid": true, + "kind": "compute", + "expect": 60.254135718484626, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [81.196705, 6.980857] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of antiquarks for a number of quarks of 81.1967 and a baryon number of 6.98086, please.", + "a": "60.254135718484626", + "valid": true, + "kind": "compute", + "expect": 60.254135718484626, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [81.196705, 6.980857] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of quarks is 19.4474 and the baryon number is 4.51548, what is the number of antiquarks?", + "a": "5.900932043264584", + "valid": true, + "kind": "compute", + "expect": 5.900932043264584, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [19.447357, 4.515475] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of antiquarks given number of quarks = 19.4474, baryon number = 4.51548?", + "a": "5.900932043264584", + "valid": true, + "kind": "compute", + "expect": 5.900932043264584, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [19.447357, 4.515475] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of antiquarks for a number of quarks of 41.2905 and a baryon number of 2.12277, please.", + "a": "34.92220394739616", + "valid": true, + "kind": "compute", + "expect": 34.92220394739616, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [41.290505, 2.122767] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of quarks is 41.2905 and the baryon number is 2.12277, what is the number of antiquarks?", + "a": "34.92220394739616", + "valid": true, + "kind": "compute", + "expect": 34.92220394739616, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [41.290505, 2.122767] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of antiquarks given number of quarks = 76.5154, baryon number = 3.14491?", + "a": "67.08067604026351", + "valid": true, + "kind": "compute", + "expect": 67.08067604026351, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [76.515411, 3.144912] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of antiquarks for a number of quarks of 76.5154 and a baryon number of 3.14491, please.", + "a": "67.08067604026351", + "valid": true, + "kind": "compute", + "expect": 67.08067604026351, + "dtype": "quantity", + "unit": "1", + "why": "number of antiquarks for [76.515411, 3.144912] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of quarks is 167.625, what is the number of antiquarks?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Could you work out the number of antiquarks given number of quarks = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Do you know the number of antiquarks 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 number of antiquarks 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 number of antiquarks given number of quarks = -81.1967, baryon number = 6.98086?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of quarks: no example had one" + }, + { + "q": "What is a typical number of antiquarks?", + "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-number-of-antiquarks/program.py b/root/organs10/physics/specialists/solved-number-of-antiquarks/program.py new file mode 100644 index 0000000000000000000000000000000000000000..983cad4b78c3eae9de7f8ae367ea2c26a9137e59 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-antiquarks/program.py @@ -0,0 +1,7 @@ +"""number of antiquarks from number of quarks, baryon number (baryon number (Wikidata Q110346)) +The maths organ (systems.py): solved from the system q2 = ((1)/(3))*( q1 - q0 ); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(number_of_quarks, baryon_number): + return -3.0*baryon_number + 1.0*number_of_quarks diff --git a/root/organs10/physics/specialists/solved-number-of-antiquarks/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-antiquarks/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-antiquarks/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-number-of-components-of-a-the/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/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-number-of-components-of-a-the/panel.json b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..96f44a9680f8ff6f8f9784d0dcfd7d07489f9962 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 107.961 and number of phases 59.4105?", + "a": "165.37116608113337", + "valid": true, + "kind": "compute", + "expect": 165.37116608113337, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [107.960666, 59.4105] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 107.961 and number of phases of 59.4105.", + "a": "165.37116608113337", + "valid": true, + "kind": "compute", + "expect": 165.37116608113337, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [107.960666, 59.4105] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 169.527 and number of phases 280.774?", + "a": "448.3006594796926", + "valid": true, + "kind": "compute", + "expect": 448.3006594796926, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [169.526958, 280.773702] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 169.527 and number of phases of 280.774.", + "a": "448.3006594796926", + "valid": true, + "kind": "compute", + "expect": 448.3006594796926, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [169.526958, 280.773702] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 1.91195 and number of phases 82.2401?", + "a": "82.15202360564845", + "valid": true, + "kind": "compute", + "expect": 82.15202360564845, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [1.911952, 82.240072] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 1.91195 and number of phases of 82.2401.", + "a": "82.15202360564845", + "valid": true, + "kind": "compute", + "expect": 82.15202360564845, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [1.911952, 82.240072] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 1.64379 and number of phases 252.709?", + "a": "252.3528197443903", + "valid": true, + "kind": "compute", + "expect": 252.3528197443903, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [1.643795, 252.709024] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 1.64379 and number of phases of 252.709.", + "a": "252.3528197443903", + "valid": true, + "kind": "compute", + "expect": 252.3528197443903, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [1.643795, 252.709024] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 18.3169 and number of phases 6.8386?", + "a": "23.155465084200447", + "valid": true, + "kind": "compute", + "expect": 23.155465084200447, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [18.316867, 6.838598] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 18.3169 and number of phases of 6.8386.", + "a": "23.155465084200447", + "valid": true, + "kind": "compute", + "expect": 23.155465084200447, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [18.316867, 6.838598] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 156.502 and number of phases 185.886?", + "a": "340.38808257181284", + "valid": true, + "kind": "compute", + "expect": 340.38808257181284, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [156.50181, 185.886273] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 156.502 and number of phases of 185.886.", + "a": "340.38808257181284", + "valid": true, + "kind": "compute", + "expect": 340.38808257181284, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [156.50181, 185.886273] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of components of a thermodynamic system for degrees of freedom 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of phases is not given" + }, + { + "q": "Tell me the number of components of a thermodynamic system with degrees of freedom of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of phases is not given" + }, + { + "q": "What is the number of components of a thermodynamic system 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 number of components of a thermodynamic system 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 number of components of a thermodynamic system with degrees of freedom of -1.91195 and number of phases of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degrees of freedom: no example had one" + }, + { + "q": "Which number of components of a thermodynamic system 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 degrees of freedom is 8.50728 and the number of phases is 17.7888, what is the number of components of a thermodynamic system?", + "a": "24.296060781565316", + "valid": true, + "kind": "compute", + "expect": 24.296060781565316, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [8.507283, 17.788778] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of components of a thermodynamic system given degrees of freedom = 8.50728, number of phases = 17.7888?", + "a": "24.296060781565316", + "valid": true, + "kind": "compute", + "expect": 24.296060781565316, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [8.507283, 17.788778] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of components of a thermodynamic system for a degrees of freedom of 8.24951 and a number of phases of 0.634021, please.", + "a": "6.8835308405523286", + "valid": true, + "kind": "compute", + "expect": 6.8835308405523286, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [8.24951, 0.634021] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 8.24951 and the number of phases is 0.634021, what is the number of components of a thermodynamic system?", + "a": "6.8835308405523286", + "valid": true, + "kind": "compute", + "expect": 6.8835308405523286, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [8.24951, 0.634021] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of components of a thermodynamic system given degrees of freedom = 0.318734, number of phases = 9.56607?", + "a": "7.884805036334958", + "valid": true, + "kind": "compute", + "expect": 7.884805036334958, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [0.318734, 9.566071] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of components of a thermodynamic system for a degrees of freedom of 0.318734 and a number of phases of 9.56607, please.", + "a": "7.884805036334958", + "valid": true, + "kind": "compute", + "expect": 7.884805036334958, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [0.318734, 9.566071] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 0.671697 and the number of phases is 14.2496, what is the number of components of a thermodynamic system?", + "a": "12.921266515731517", + "valid": true, + "kind": "compute", + "expect": 12.921266515731517, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [0.671697, 14.249569] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of components of a thermodynamic system given degrees of freedom = 0.671697, number of phases = 14.2496?", + "a": "12.921266515731517", + "valid": true, + "kind": "compute", + "expect": 12.921266515731517, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [0.671697, 14.249569] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of components of a thermodynamic system for a degrees of freedom of 21.7931 and a number of phases of 29.5106, please.", + "a": "49.30373515218151", + "valid": true, + "kind": "compute", + "expect": 49.30373515218151, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [21.793126, 29.510609] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 21.7931 and the number of phases is 29.5106, what is the number of components of a thermodynamic system?", + "a": "49.30373515218151", + "valid": true, + "kind": "compute", + "expect": 49.30373515218151, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [21.793126, 29.510609] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of components of a thermodynamic system given degrees of freedom = 153.15, number of phases = 18.5953?", + "a": "169.745280607835", + "valid": true, + "kind": "compute", + "expect": 169.745280607835, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [153.149965, 18.595315] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of components of a thermodynamic system for a degrees of freedom of 153.15 and a number of phases of 18.5953, please.", + "a": "169.745280607835", + "valid": true, + "kind": "compute", + "expect": 169.745280607835, + "dtype": "quantity", + "unit": "1", + "why": "number of components of a thermodynamic system for [153.149965, 18.595315] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 8.50728, what is the number of components of a thermodynamic system?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of phases is not given" + }, + { + "q": "Could you work out the number of components of a thermodynamic system given degrees of freedom = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of phases is not given" + }, + { + "q": "Do you know the number of components of a thermodynamic system 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 number of components of a thermodynamic system 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 number of components of a thermodynamic system given degrees of freedom = -0.318734, number of phases = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degrees of freedom: no example had one" + }, + { + "q": "What is a typical number of components of a thermodynamic system?", + "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-number-of-components-of-a-the/program.py b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/program.py new file mode 100644 index 0000000000000000000000000000000000000000..21ed1875d9b2548c2af7c7b7df2c88a2ccfcf236 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/program.py @@ -0,0 +1,7 @@ +"""number of components of a thermodynamic system from degrees of freedom, number of phases (Gibbs' phase rule (Wikidata Q752412)) +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(degrees_of_freedom, number_of_phases): + return 1.0*degrees_of_freedom + 1.0*number_of_phases - 2.0 diff --git a/root/organs10/physics/specialists/solved-number-of-components-of-a-the/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-components-of-a-the/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-number-of-dissociated-molecul/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/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-number-of-dissociated-molecul/panel.json b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..9770248b82e8ebcb0aeb5f00f20241536d4100ad --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of dissociated molecules for degree of dissociation 107.961 and number of molecules 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [107.960666, 59.4105] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 107.961 and number of molecules of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [107.960666, 59.4105] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 169.527 and number of molecules 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [169.526958, 280.773702] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 169.527 and number of molecules of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [169.526958, 280.773702] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 1.91195 and number of molecules 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [1.911952, 82.240072] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 1.91195 and number of molecules of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [1.911952, 82.240072] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 1.64379 and number of molecules 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [1.643795, 252.709024] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 1.64379 and number of molecules of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [1.643795, 252.709024] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 18.3169 and number of molecules 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [18.316867, 6.838598] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 18.3169 and number of molecules of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [18.316867, 6.838598] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 156.502 and number of molecules 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [156.50181, 185.886273] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 156.502 and number of molecules of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [156.50181, 185.886273] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of dissociated molecules for degree of dissociation 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of molecules is not given" + }, + { + "q": "Tell me the number of dissociated molecules with degree of dissociation of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of molecules is not given" + }, + { + "q": "What is the number of dissociated molecules 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 number of dissociated molecules 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 number of dissociated molecules with degree of dissociation of -1.91195 and number of molecules of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degree of dissociation: no example had one" + }, + { + "q": "Which number of dissociated molecules 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 degree of dissociation is 8.50728 and the number of molecules is 17.7888, what is the number of dissociated molecules?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [8.507283, 17.788778] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of dissociated molecules given degree of dissociation = 8.50728, number of molecules = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [8.507283, 17.788778] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of dissociated molecules for a degree of dissociation of 8.24951 and a number of molecules of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [8.24951, 0.634021] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the degree of dissociation is 8.24951 and the number of molecules is 0.634021, what is the number of dissociated molecules?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [8.24951, 0.634021] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of dissociated molecules given degree of dissociation = 0.318734, number of molecules = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [0.318734, 9.566071] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of dissociated molecules for a degree of dissociation of 0.318734 and a number of molecules of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [0.318734, 9.566071] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the degree of dissociation is 0.671697 and the number of molecules is 14.2496, what is the number of dissociated molecules?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [0.671697, 14.249569] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of dissociated molecules given degree of dissociation = 0.671697, number of molecules = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [0.671697, 14.249569] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of dissociated molecules for a degree of dissociation of 21.7931 and a number of molecules of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [21.793126, 29.510609] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the degree of dissociation is 21.7931 and the number of molecules is 29.5106, what is the number of dissociated molecules?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [21.793126, 29.510609] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of dissociated molecules given degree of dissociation = 153.15, number of molecules = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [153.149965, 18.595315] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of dissociated molecules for a degree of dissociation of 153.15 and a number of molecules of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "number of dissociated molecules for [153.149965, 18.595315] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the degree of dissociation is 8.50728, what is the number of dissociated molecules?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of molecules is not given" + }, + { + "q": "Could you work out the number of dissociated molecules given degree of dissociation = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of molecules is not given" + }, + { + "q": "Do you know the number of dissociated molecules 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 number of dissociated molecules 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 number of dissociated molecules given degree of dissociation = -0.318734, number of molecules = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degree of dissociation: no example had one" + }, + { + "q": "What is a typical number of dissociated molecules?", + "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-number-of-dissociated-molecul/program.py b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/program.py new file mode 100644 index 0000000000000000000000000000000000000000..92bf667964f5a20a365571ae4182847dcca3dffb --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/program.py @@ -0,0 +1,7 @@ +"""number of dissociated molecules from degree of dissociation, number of molecules (degree of dissociation (Wikidata Q907334)) +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(degree_of_dissociation, number_of_molecules): + return 1.0*degree_of_dissociation*number_of_molecules diff --git a/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-dissociated-molecul/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-number-of-entities-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-entities-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-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-number-of-entities-2/panel.json b/root/organs10/physics/specialists/solved-number-of-entities-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..011b01734c5cef38d0bd9962866d130730df6ff8 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of entities for amount of substance 107.961?", + "a": "6.501543265326808e+25", + "valid": true, + "kind": "compute", + "expect": 6.501543265326808e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 107.961.", + "a": "6.501543265326808e+25", + "valid": true, + "kind": "compute", + "expect": 6.501543265326808e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities for amount of substance 22.652?", + "a": "1.3641366978139424e+25", + "valid": true, + "kind": "compute", + "expect": 1.3641366978139424e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [22.652023] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 22.652.", + "a": "1.3641366978139424e+25", + "valid": true, + "kind": "compute", + "expect": 1.3641366978139424e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [22.652023] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities for amount of substance 173.394?", + "a": "1.044200897365272e+26", + "valid": true, + "kind": "compute", + "expect": 1.044200897365272e+26, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [173.393638] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 173.394.", + "a": "1.044200897365272e+26", + "valid": true, + "kind": "compute", + "expect": 1.044200897365272e+26, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [173.393638] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities for amount of substance 126.709?", + "a": "7.630609499349803e+25", + "valid": true, + "kind": "compute", + "expect": 7.630609499349803e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [126.709252] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 126.709.", + "a": "7.630609499349803e+25", + "valid": true, + "kind": "compute", + "expect": 7.630609499349803e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [126.709252] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities for amount of substance 0.671697?", + "a": "4.0450550852584696e+23", + "valid": true, + "kind": "compute", + "expect": 4.0450550852584696e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 0.671697.", + "a": "4.0450550852584696e+23", + "valid": true, + "kind": "compute", + "expect": 4.0450550852584696e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities for amount of substance 1.16997?", + "a": "7.045712016695639e+23", + "valid": true, + "kind": "compute", + "expect": 7.045712016695639e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.169968] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Tell me the number of entities with amount of substance of 1.16997.", + "a": "7.045712016695639e+23", + "valid": true, + "kind": "compute", + "expect": 7.045712016695639e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.169968] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "What is the number of entities?", + "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 number of entities, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "What is the number of entities 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 number of entities 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 number of entities with amount of substance of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount of substance: no example had one" + }, + { + "q": "Which number of entities 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 amount of substance is 2.57003, what is the number of entities?", + "a": "1.5477081895325114e+24", + "valid": true, + "kind": "compute", + "expect": 1.5477081895325114e+24, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [2.57003] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Could you work out the number of entities given amount of substance = 2.57003?", + "a": "1.5477081895325114e+24", + "valid": true, + "kind": "compute", + "expect": 1.5477081895325114e+24, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [2.57003] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "I need the number of entities for an amount of substance of 48.921, please.", + "a": "2.9460909307766423e+25", + "valid": true, + "kind": "compute", + "expect": 2.9460909307766423e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [48.920991] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "If the amount of substance is 48.921, what is the number of entities?", + "a": "2.9460909307766423e+25", + "valid": true, + "kind": "compute", + "expect": 2.9460909307766423e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [48.920991] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Could you work out the number of entities given amount of substance = 0.348438?", + "a": "2.098340692598417e+23", + "valid": true, + "kind": "compute", + "expect": 2.098340692598417e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.348438] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "I need the number of entities for an amount of substance of 0.348438, please.", + "a": "2.098340692598417e+23", + "valid": true, + "kind": "compute", + "expect": 2.098340692598417e+23, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.348438] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "If the amount of substance is 252.709, what is the number of entities?", + "a": "1.5218493153529055e+26", + "valid": true, + "kind": "compute", + "expect": 1.5218493153529055e+26, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [252.709024] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Could you work out the number of entities given amount of substance = 252.709?", + "a": "1.5218493153529055e+26", + "valid": true, + "kind": "compute", + "expect": 1.5218493153529055e+26, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [252.709024] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "I need the number of entities for an amount of substance of 20.3966, please.", + "a": "1.2283094306644234e+25", + "valid": true, + "kind": "compute", + "expect": 1.2283094306644234e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [20.396558] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "If the amount of substance is 20.3966, what is the number of entities?", + "a": "1.2283094306644234e+25", + "valid": true, + "kind": "compute", + "expect": 1.2283094306644234e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [20.396558] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "Could you work out the number of entities given amount of substance = 134.993?", + "a": "8.129465921599118e+25", + "valid": true, + "kind": "compute", + "expect": 8.129465921599118e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [134.992958] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "I need the number of entities for an amount of substance of 134.993, please.", + "a": "8.129465921599118e+25", + "valid": true, + "kind": "compute", + "expect": 8.129465921599118e+25, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [134.992958] (the system amount of substance (Wikidata Q104946))" + }, + { + "q": "I need the number of entities, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Can you tell me the number of entities?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the amount of substance is not given" + }, + { + "q": "Do you know the number of entities 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 number of entities 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 number of entities given amount of substance = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount of substance: no example had one" + }, + { + "q": "What is a typical number of entities?", + "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-number-of-entities-2/program.py b/root/organs10/physics/specialists/solved-number-of-entities-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..953a78ba22a08b41cb5ed5311a34497d308c69fc --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-2/program.py @@ -0,0 +1,7 @@ +"""number of entities from amount of substance (amount of substance (Wikidata Q104946)) +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(amount_of_substance): + return 6.02214075999999e+23*amount_of_substance diff --git a/root/organs10/physics/specialists/solved-number-of-entities-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-entities-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-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-number-of-entities-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-entities-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-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-number-of-entities-3/panel.json b/root/organs10/physics/specialists/solved-number-of-entities-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7b094f899656a8fa1615b77193b36ba6c65ac5da --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of entities for mean energy imparted 107.961 and G-value 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666, 59.4105] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 107.961 and G-value of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666, 59.4105] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 169.527 and G-value 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [169.526958, 280.773702] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 169.527 and G-value of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [169.526958, 280.773702] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 1.91195 and G-value 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.911952, 82.240072] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 1.91195 and G-value of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.911952, 82.240072] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 1.64379 and G-value 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.643795, 252.709024] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 1.64379 and G-value of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.643795, 252.709024] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 18.3169 and G-value 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [18.316867, 6.838598] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 18.3169 and G-value of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [18.316867, 6.838598] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 156.502 and G-value 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [156.50181, 185.886273] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 156.502 and G-value of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [156.50181, 185.886273] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "What is the number of entities for mean energy imparted 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the G-value is not given" + }, + { + "q": "Tell me the number of entities with mean energy imparted of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the G-value is not given" + }, + { + "q": "What is the number of entities 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 number of entities 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 number of entities with mean energy imparted of -1.91195 and G-value 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 number of entities 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 G-value is 17.7888, what is the number of entities?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.507283, 17.788778] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Could you work out the number of entities given mean energy imparted = 8.50728, G-value = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.507283, 17.788778] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "I need the number of entities for a mean energy imparted of 8.24951 and a G-value of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.24951, 0.634021] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "If the mean energy imparted is 8.24951 and the G-value is 0.634021, what is the number of entities?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.24951, 0.634021] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Could you work out the number of entities given mean energy imparted = 0.318734, G-value = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.318734, 9.566071] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "I need the number of entities for a mean energy imparted of 0.318734 and a G-value of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.318734, 9.566071] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "If the mean energy imparted is 0.671697 and the G-value is 14.2496, what is the number of entities?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697, 14.249569] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Could you work out the number of entities given mean energy imparted = 0.671697, G-value = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697, 14.249569] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "I need the number of entities for a mean energy imparted of 21.7931 and a G-value of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [21.793126, 29.510609] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "If the mean energy imparted is 21.7931 and the G-value is 29.5106, what is the number of entities?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [21.793126, 29.510609] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "Could you work out the number of entities given mean energy imparted = 153.15, G-value = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [153.149965, 18.595315] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "I need the number of entities for a mean energy imparted of 153.15 and a G-value of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [153.149965, 18.595315] (the system G-value (Wikidata Q15811154))" + }, + { + "q": "If the mean energy imparted is 8.50728, what is the number of entities?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the G-value is not given" + }, + { + "q": "Could you work out the number of entities given mean energy imparted = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the G-value is not given" + }, + { + "q": "Do you know the number of entities 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 number of entities 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 number of entities given mean energy imparted = -0.318734, G-value = 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 number of entities?", + "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-number-of-entities-3/program.py b/root/organs10/physics/specialists/solved-number-of-entities-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5d41521b8ecb1718eecfc254b7f52d13c9a62f11 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-3/program.py @@ -0,0 +1,7 @@ +"""number of entities from mean energy imparted, G-value (G-value (Wikidata Q15811154)) +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, g_value): + return 1.0*g_value*mean_energy_imparted diff --git a/root/organs10/physics/specialists/solved-number-of-entities-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-entities-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-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-number-of-entities-per-area/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-entities-per-area/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-per-area/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-number-of-entities-per-area/panel.json b/root/organs10/physics/specialists/solved-number-of-entities-per-area/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3de7ac9f2bf711633e01e3fb934d33570030fd69 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-per-area/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of entities per area for number of entities 107.961 and area 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [107.960666, 59.4105] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 107.961 and area of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [107.960666, 59.4105] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 169.527 and area 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [169.526958, 280.773702] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 169.527 and area of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [169.526958, 280.773702] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 1.91195 and area 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [1.911952, 82.240072] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 1.91195 and area of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [1.911952, 82.240072] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 1.64379 and area 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [1.643795, 252.709024] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 1.64379 and area of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [1.643795, 252.709024] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 18.3169 and area 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [18.316867, 6.838598] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 18.3169 and area of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [18.316867, 6.838598] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 156.502 and area 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [156.50181, 185.886273] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities per area with number of entities of 156.502 and area of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [156.50181, 185.886273] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities per area for number of entities 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the number of entities per area with number of entities of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the number of entities per area 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 number of entities per area 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 number of entities per area with number of entities of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of entities: no example had one" + }, + { + "q": "Which number of entities per area 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 number of entities is 8.50728 and the area is 17.7888, what is the number of entities per area?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [8.507283, 17.788778] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities per area given number of entities = 8.50728, area = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [8.507283, 17.788778] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities per area for a number of entities of 8.24951 and an area of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [8.24951, 0.634021] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities is 8.24951 and the area is 0.634021, what is the number of entities per area?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [8.24951, 0.634021] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities per area given number of entities = 0.318734, area = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [0.318734, 9.566071] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities per area for a number of entities of 0.318734 and an area of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [0.318734, 9.566071] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities is 0.671697 and the area is 14.2496, what is the number of entities per area?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [0.671697, 14.249569] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities per area given number of entities = 0.671697, area = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [0.671697, 14.249569] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities per area for a number of entities of 21.7931 and an area of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [21.793126, 29.510609] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities is 21.7931 and the area is 29.5106, what is the number of entities per area?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [21.793126, 29.510609] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities per area given number of entities = 153.15, area = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [153.149965, 18.595315] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities per area for a number of entities of 153.15 and an area of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1/m^2", + "why": "number of entities per area for [153.149965, 18.595315] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities is 8.50728, what is the number of entities per area?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the number of entities per area given number of entities = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the number of entities per area 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 number of entities per area 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 number of entities per area given number of entities = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of entities: no example had one" + }, + { + "q": "What is a typical number of entities per area?", + "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-number-of-entities-per-area/program.py b/root/organs10/physics/specialists/solved-number-of-entities-per-area/program.py new file mode 100644 index 0000000000000000000000000000000000000000..06246ff3211ae75fbe84dbc28037adc84628d509 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-per-area/program.py @@ -0,0 +1,7 @@ +"""number of entities per area from number of entities, area (number of entities per area (Wikidata Q108914597)) +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(number_of_entities, area): + return 1.0*number_of_entities/area diff --git a/root/organs10/physics/specialists/solved-number-of-entities-per-area/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-entities-per-area/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities-per-area/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-number-of-entities/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-entities/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities/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-number-of-entities/panel.json b/root/organs10/physics/specialists/solved-number-of-entities/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..82617067111b6d79361843d16814dc801e7523cc --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of entities for number of entities per area 107.961 and area 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666, 59.4105] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 107.961 and area of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [107.960666, 59.4105] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 169.527 and area 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [169.526958, 280.773702] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 169.527 and area of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [169.526958, 280.773702] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 1.91195 and area 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.911952, 82.240072] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 1.91195 and area of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.911952, 82.240072] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 1.64379 and area 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.643795, 252.709024] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 1.64379 and area of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [1.643795, 252.709024] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 18.3169 and area 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [18.316867, 6.838598] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 18.3169 and area of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [18.316867, 6.838598] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 156.502 and area 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [156.50181, 185.886273] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Tell me the number of entities with number of entities per area of 156.502 and area of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [156.50181, 185.886273] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "What is the number of entities for number of entities per area 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Tell me the number of entities with number of entities per area of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "What is the number of entities 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 number of entities 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 number of entities with number of entities per area of -1.91195 and area of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of entities per area: no example had one" + }, + { + "q": "Which number of entities 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 number of entities per area is 8.50728 and the area is 17.7888, what is the number of entities?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.507283, 17.788778] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities given number of entities per area = 8.50728, area = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.507283, 17.788778] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities for a number of entities per area of 8.24951 and an area of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.24951, 0.634021] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities per area is 8.24951 and the area is 0.634021, what is the number of entities?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [8.24951, 0.634021] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities given number of entities per area = 0.318734, area = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.318734, 9.566071] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities for a number of entities per area 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": "number of entities for [0.318734, 9.566071] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities per area is 0.671697 and the area is 14.2496, what is the number of entities?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697, 14.249569] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities given number of entities per area = 0.671697, area = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [0.671697, 14.249569] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities for a number of entities per area 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": "number of entities for [21.793126, 29.510609] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities per area is 21.7931 and the area is 29.5106, what is the number of entities?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [21.793126, 29.510609] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "Could you work out the number of entities given number of entities per area = 153.15, area = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "1", + "why": "number of entities for [153.149965, 18.595315] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "I need the number of entities for a number of entities per area 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": "number of entities for [153.149965, 18.595315] (the system number of entities per area (Wikidata Q108914597))" + }, + { + "q": "If the number of entities per area is 8.50728, what is the number of entities?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Could you work out the number of entities given number of entities per area = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the area is not given" + }, + { + "q": "Do you know the number of entities 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 number of entities 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 number of entities given number of entities per area = -0.318734, area = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of entities per area: no example had one" + }, + { + "q": "What is a typical number of entities?", + "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-number-of-entities/program.py b/root/organs10/physics/specialists/solved-number-of-entities/program.py new file mode 100644 index 0000000000000000000000000000000000000000..17096e435411f581c0e9b4c59d4d88ee1985b9d7 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities/program.py @@ -0,0 +1,7 @@ +"""number of entities from number of entities per area, area (number of entities per area (Wikidata Q108914597)) +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(number_of_entities_per_area, area): + return 1.0*area*number_of_entities_per_area diff --git a/root/organs10/physics/specialists/solved-number-of-entities/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-entities/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-entities/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-number-of-molecules/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-molecules/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-molecules/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-number-of-molecules/panel.json b/root/organs10/physics/specialists/solved-number-of-molecules/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..3ae3e27b3498a07b7823386df17d6bc7d12310cd --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-molecules/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of molecules for number of dissociated molecules 107.961 and degree of dissociation 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [107.960666, 59.4105] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 107.961 and degree of dissociation of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [107.960666, 59.4105] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 169.527 and degree of dissociation 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [169.526958, 280.773702] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 169.527 and degree of dissociation of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [169.526958, 280.773702] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 1.91195 and degree of dissociation 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [1.911952, 82.240072] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 1.91195 and degree of dissociation of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [1.911952, 82.240072] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 1.64379 and degree of dissociation 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [1.643795, 252.709024] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 1.64379 and degree of dissociation of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [1.643795, 252.709024] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 18.3169 and degree of dissociation 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [18.316867, 6.838598] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 18.3169 and degree of dissociation of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [18.316867, 6.838598] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 156.502 and degree of dissociation 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [156.50181, 185.886273] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 156.502 and degree of dissociation of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [156.50181, 185.886273] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "What is the number of molecules for number of dissociated molecules 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the degree of dissociation is not given" + }, + { + "q": "Tell me the number of molecules with number of dissociated molecules of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the degree of dissociation is not given" + }, + { + "q": "What is the number of molecules 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 number of molecules 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 number of molecules with number of dissociated molecules of -1.91195 and degree of dissociation of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of dissociated molecules: no example had one" + }, + { + "q": "Which number of molecules 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 number of dissociated molecules is 8.50728 and the degree of dissociation is 17.7888, what is the number of molecules?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [8.507283, 17.788778] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of molecules given number of dissociated molecules = 8.50728, degree of dissociation = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [8.507283, 17.788778] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of molecules for a number of dissociated molecules of 8.24951 and a degree of dissociation of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [8.24951, 0.634021] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the number of dissociated molecules is 8.24951 and the degree of dissociation is 0.634021, what is the number of molecules?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [8.24951, 0.634021] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of molecules given number of dissociated molecules = 0.318734, degree of dissociation = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [0.318734, 9.566071] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of molecules for a number of dissociated molecules of 0.318734 and a degree of dissociation of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [0.318734, 9.566071] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the number of dissociated molecules is 0.671697 and the degree of dissociation is 14.2496, what is the number of molecules?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [0.671697, 14.249569] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of molecules given number of dissociated molecules = 0.671697, degree of dissociation = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [0.671697, 14.249569] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of molecules for a number of dissociated molecules of 21.7931 and a degree of dissociation of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [21.793126, 29.510609] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the number of dissociated molecules is 21.7931 and the degree of dissociation is 29.5106, what is the number of molecules?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [21.793126, 29.510609] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "Could you work out the number of molecules given number of dissociated molecules = 153.15, degree of dissociation = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [153.149965, 18.595315] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "I need the number of molecules for a number of dissociated molecules of 153.15 and a degree of dissociation of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "1", + "why": "number of molecules for [153.149965, 18.595315] (the system degree of dissociation (Wikidata Q907334))" + }, + { + "q": "If the number of dissociated molecules is 8.50728, what is the number of molecules?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the degree of dissociation is not given" + }, + { + "q": "Could you work out the number of molecules given number of dissociated molecules = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the degree of dissociation is not given" + }, + { + "q": "Do you know the number of molecules 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 number of molecules 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 number of molecules given number of dissociated molecules = -0.318734, degree of dissociation = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of dissociated molecules: no example had one" + }, + { + "q": "What is a typical number of molecules?", + "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-number-of-molecules/program.py b/root/organs10/physics/specialists/solved-number-of-molecules/program.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd154a983fb0a560ee3db45a639237dffcfc69f --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-molecules/program.py @@ -0,0 +1,7 @@ +"""number of molecules from number of dissociated molecules, degree of dissociation (degree of dissociation (Wikidata Q907334)) +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(number_of_dissociated_molecules, degree_of_dissociation): + return 1.0*number_of_dissociated_molecules/degree_of_dissociation diff --git a/root/organs10/physics/specialists/solved-number-of-molecules/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-molecules/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-molecules/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-number-of-phases/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-phases/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-phases/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-number-of-phases/panel.json b/root/organs10/physics/specialists/solved-number-of-phases/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7b3669955fc28846b3a45eee41858854c123e710 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-phases/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of phases for degrees of freedom 8.50728 and number of components of a thermodynamic system 17.7888?", + "a": "11.281495473483474", + "valid": true, + "kind": "compute", + "expect": 11.281495473483474, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [8.507283, 17.788778] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 8.50728 and number of components of a thermodynamic system of 17.7888.", + "a": "11.281495473483474", + "valid": true, + "kind": "compute", + "expect": 11.281495473483474, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [8.507283, 17.788778] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 6.34623 and number of components of a thermodynamic system 21.511?", + "a": "17.16479025695291", + "valid": true, + "kind": "compute", + "expect": 17.16479025695291, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [6.346226, 21.511016] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 6.34623 and number of components of a thermodynamic system of 21.511.", + "a": "17.16479025695291", + "valid": true, + "kind": "compute", + "expect": 17.16479025695291, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [6.346226, 21.511016] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 1.64379 and number of components of a thermodynamic system 252.709?", + "a": "253.06522875466473", + "valid": true, + "kind": "compute", + "expect": 253.06522875466473, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [1.643795, 252.709024] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 1.64379 and number of components of a thermodynamic system of 252.709.", + "a": "253.06522875466473", + "valid": true, + "kind": "compute", + "expect": 253.06522875466473, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [1.643795, 252.709024] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 1.16997 and number of components of a thermodynamic system 1.14865?", + "a": "1.9786842893671603", + "valid": true, + "kind": "compute", + "expect": 1.9786842893671603, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [1.169968, 1.148652] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 1.16997 and number of components of a thermodynamic system of 1.14865.", + "a": "1.9786842893671603", + "valid": true, + "kind": "compute", + "expect": 1.9786842893671603, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [1.169968, 1.148652] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 7.10705 and number of components of a thermodynamic system 30.2507?", + "a": "25.143700093865256", + "valid": true, + "kind": "compute", + "expect": 25.143700093865256, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [7.107049, 30.250749] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 7.10705 and number of components of a thermodynamic system of 30.2507.", + "a": "25.143700093865256", + "valid": true, + "kind": "compute", + "expect": 25.143700093865256, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [7.107049, 30.250749] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 0.869111 and number of components of a thermodynamic system 39.1753?", + "a": "40.3061515435122", + "valid": true, + "kind": "compute", + "expect": 40.3061515435122, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.869111, 39.175263] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 0.869111 and number of components of a thermodynamic system of 39.1753.", + "a": "40.3061515435122", + "valid": true, + "kind": "compute", + "expect": 40.3061515435122, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.869111, 39.175263] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "What is the number of phases for degrees of freedom 8.50728?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of components of a thermodynamic system is not given" + }, + { + "q": "Tell me the number of phases with degrees of freedom of 6.34623.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of components of a thermodynamic system is not given" + }, + { + "q": "What is the number of phases 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 number of phases 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 number of phases with degrees of freedom of -1.64379 and number of components of a thermodynamic system of 252.709.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degrees of freedom: no example had one" + }, + { + "q": "Which number of phases 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 degrees of freedom is 169.527 and the number of components of a thermodynamic system is 280.774, what is the number of phases?", + "a": "113.24674440201241", + "valid": true, + "kind": "compute", + "expect": 113.24674440201241, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [169.526958, 280.773702] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of phases given degrees of freedom = 169.527, number of components of a thermodynamic system = 280.774?", + "a": "113.24674440201241", + "valid": true, + "kind": "compute", + "expect": 113.24674440201241, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [169.526958, 280.773702] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of phases for a degrees of freedom of 0.318734 and a number of components of a thermodynamic system of 9.56607, please.", + "a": "11.24733694103161", + "valid": true, + "kind": "compute", + "expect": 11.24733694103161, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.318734, 9.566071] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 0.318734 and the number of components of a thermodynamic system is 9.56607, what is the number of phases?", + "a": "11.24733694103161", + "valid": true, + "kind": "compute", + "expect": 11.24733694103161, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.318734, 9.566071] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of phases given degrees of freedom = 0.671697, number of components of a thermodynamic system = 14.2496?", + "a": "15.57787211614313", + "valid": true, + "kind": "compute", + "expect": 15.57787211614313, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.671697, 14.249569] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of phases for a degrees of freedom of 0.671697 and a number of components of a thermodynamic system of 14.2496, please.", + "a": "15.57787211614313", + "valid": true, + "kind": "compute", + "expect": 15.57787211614313, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [0.671697, 14.249569] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 156.502 and the number of components of a thermodynamic system is 185.886, what is the number of phases?", + "a": "31.38446301183552", + "valid": true, + "kind": "compute", + "expect": 31.38446301183552, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [156.50181, 185.886273] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of phases given degrees of freedom = 156.502, number of components of a thermodynamic system = 185.886?", + "a": "31.38446301183552", + "valid": true, + "kind": "compute", + "expect": 31.38446301183552, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [156.50181, 185.886273] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of phases for a degrees of freedom of 24.5721 and a number of components of a thermodynamic system of 108.451, please.", + "a": "85.87870607231024", + "valid": true, + "kind": "compute", + "expect": 85.87870607231024, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [24.572086, 108.450792] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 24.5721 and the number of components of a thermodynamic system is 108.451, what is the number of phases?", + "a": "85.87870607231024", + "valid": true, + "kind": "compute", + "expect": 85.87870607231024, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [24.572086, 108.450792] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "Could you work out the number of phases given degrees of freedom = 4.07774, number of components of a thermodynamic system = 276.408?", + "a": "274.32983938133856", + "valid": true, + "kind": "compute", + "expect": 274.32983938133856, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [4.077743, 276.407582] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "I need the number of phases for a degrees of freedom of 4.07774 and a number of components of a thermodynamic system of 276.408, please.", + "a": "274.32983938133856", + "valid": true, + "kind": "compute", + "expect": 274.32983938133856, + "dtype": "quantity", + "unit": "1", + "why": "number of phases for [4.077743, 276.407582] (the system Gibbs' phase rule (Wikidata Q752412))" + }, + { + "q": "If the degrees of freedom is 169.527, what is the number of phases?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of components of a thermodynamic system is not given" + }, + { + "q": "Could you work out the number of phases given degrees of freedom = 0.318734?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the number of components of a thermodynamic system is not given" + }, + { + "q": "Do you know the number of phases 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 number of phases 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 number of phases given degrees of freedom = -0.671697, number of components of a thermodynamic system = 14.2496?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative degrees of freedom: no example had one" + }, + { + "q": "What is a typical number of phases?", + "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-number-of-phases/program.py b/root/organs10/physics/specialists/solved-number-of-phases/program.py new file mode 100644 index 0000000000000000000000000000000000000000..cecd8e564055b7a70406454731175ab52c65c85e --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-phases/program.py @@ -0,0 +1,7 @@ +"""number of phases from degrees of freedom, number of components of a thermodynamic system (Gibbs' phase rule (Wikidata Q752412)) +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(degrees_of_freedom, number_of_components_of_a_thermodynamic_system): + return -1.0*degrees_of_freedom + 1.0*number_of_components_of_a_thermodynamic_system + 2.0 diff --git a/root/organs10/physics/specialists/solved-number-of-phases/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-phases/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-phases/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-number-of-quarks/organ_formula_v2.py b/root/organs10/physics/specialists/solved-number-of-quarks/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-quarks/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-number-of-quarks/panel.json b/root/organs10/physics/specialists/solved-number-of-quarks/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5b7b98add0d6f447d9352324ee1000c2638c2355 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-quarks/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the number of quarks for number of antiquarks 107.961 and baryon number 59.4105?", + "a": "286.19216646347604", + "valid": true, + "kind": "compute", + "expect": 286.19216646347604, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [107.960666, 59.4105] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 107.961 and baryon number of 59.4105.", + "a": "286.19216646347604", + "valid": true, + "kind": "compute", + "expect": 286.19216646347604, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [107.960666, 59.4105] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 169.527 and baryon number 280.774?", + "a": "1011.8480633613975", + "valid": true, + "kind": "compute", + "expect": 1011.8480633613975, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [169.526958, 280.773702] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 169.527 and baryon number of 280.774.", + "a": "1011.8480633613975", + "valid": true, + "kind": "compute", + "expect": 1011.8480633613975, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [169.526958, 280.773702] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 1.91195 and baryon number 82.2401?", + "a": "248.6321672909729", + "valid": true, + "kind": "compute", + "expect": 248.6321672909729, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [1.911952, 82.240072] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 1.91195 and baryon number of 82.2401.", + "a": "248.6321672909729", + "valid": true, + "kind": "compute", + "expect": 248.6321672909729, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [1.911952, 82.240072] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 1.64379 and baryon number 252.709?", + "a": "759.7708682434454", + "valid": true, + "kind": "compute", + "expect": 759.7708682434454, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [1.643795, 252.709024] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 1.64379 and baryon number of 252.709.", + "a": "759.7708682434454", + "valid": true, + "kind": "compute", + "expect": 759.7708682434454, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [1.643795, 252.709024] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 18.3169 and baryon number 6.8386?", + "a": "38.832661207048304", + "valid": true, + "kind": "compute", + "expect": 38.832661207048304, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [18.316867, 6.838598] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 18.3169 and baryon number of 6.8386.", + "a": "38.832661207048304", + "valid": true, + "kind": "compute", + "expect": 38.832661207048304, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [18.316867, 6.838598] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 156.502 and baryon number 185.886?", + "a": "714.1606281554612", + "valid": true, + "kind": "compute", + "expect": 714.1606281554612, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [156.50181, 185.886273] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 156.502 and baryon number of 185.886.", + "a": "714.1606281554612", + "valid": true, + "kind": "compute", + "expect": 714.1606281554612, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [156.50181, 185.886273] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "What is the number of quarks for number of antiquarks 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Tell me the number of quarks with number of antiquarks of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "What is the number of quarks 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 number of quarks 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 number of quarks with number of antiquarks of -1.91195 and baryon number of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of antiquarks: no example had one" + }, + { + "q": "Which number of quarks 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 number of antiquarks is 8.50728 and the baryon number is 17.7888, what is the number of quarks?", + "a": "61.87361703661411", + "valid": true, + "kind": "compute", + "expect": 61.87361703661411, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [8.507283, 17.788778] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of quarks given number of antiquarks = 8.50728, baryon number = 17.7888?", + "a": "61.87361703661411", + "valid": true, + "kind": "compute", + "expect": 61.87361703661411, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [8.507283, 17.788778] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of quarks for a number of antiquarks of 8.24951 and a baryon number of 0.634021, please.", + "a": "10.151572786282903", + "valid": true, + "kind": "compute", + "expect": 10.151572786282903, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [8.24951, 0.634021] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of antiquarks is 8.24951 and the baryon number is 0.634021, what is the number of quarks?", + "a": "10.151572786282903", + "valid": true, + "kind": "compute", + "expect": 10.151572786282903, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [8.24951, 0.634021] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of quarks given number of antiquarks = 0.318734, baryon number = 9.56607?", + "a": "29.016947013701525", + "valid": true, + "kind": "compute", + "expect": 29.016947013701525, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [0.318734, 9.566071] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of quarks for a number of antiquarks of 0.318734 and a baryon number of 9.56607, please.", + "a": "29.016947013701525", + "valid": true, + "kind": "compute", + "expect": 29.016947013701525, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [0.318734, 9.566071] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of antiquarks is 0.671697 and the baryon number is 14.2496, what is the number of quarks?", + "a": "43.42040514760617", + "valid": true, + "kind": "compute", + "expect": 43.42040514760617, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [0.671697, 14.249569] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of quarks given number of antiquarks = 0.671697, baryon number = 14.2496?", + "a": "43.42040514760617", + "valid": true, + "kind": "compute", + "expect": 43.42040514760617, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [0.671697, 14.249569] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of quarks for a number of antiquarks of 21.7931 and a baryon number of 29.5106, please.", + "a": "110.32495247197288", + "valid": true, + "kind": "compute", + "expect": 110.32495247197288, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [21.793126, 29.510609] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of antiquarks is 21.7931 and the baryon number is 29.5106, what is the number of quarks?", + "a": "110.32495247197288", + "valid": true, + "kind": "compute", + "expect": 110.32495247197288, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [21.793126, 29.510609] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "Could you work out the number of quarks given number of antiquarks = 153.15, baryon number = 18.5953?", + "a": "208.93591154946688", + "valid": true, + "kind": "compute", + "expect": 208.93591154946688, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [153.149965, 18.595315] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "I need the number of quarks for a number of antiquarks of 153.15 and a baryon number of 18.5953, please.", + "a": "208.93591154946688", + "valid": true, + "kind": "compute", + "expect": 208.93591154946688, + "dtype": "quantity", + "unit": "1", + "why": "number of quarks for [153.149965, 18.595315] (the system baryon number (Wikidata Q110346))" + }, + { + "q": "If the number of antiquarks is 8.50728, what is the number of quarks?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Could you work out the number of quarks given number of antiquarks = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the baryon number is not given" + }, + { + "q": "Do you know the number of quarks 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 number of quarks 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 number of quarks given number of antiquarks = -0.318734, baryon number = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative number of antiquarks: no example had one" + }, + { + "q": "What is a typical number of quarks?", + "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-number-of-quarks/program.py b/root/organs10/physics/specialists/solved-number-of-quarks/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d99aa828cb526747934325cd09950f7f8d438f59 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-quarks/program.py @@ -0,0 +1,7 @@ +"""number of quarks from number of antiquarks, baryon number (baryon number (Wikidata Q110346)) +The maths organ (systems.py): solved from the system q2 = ((1)/(3))*( q1 - q0 ); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(number_of_antiquarks, baryon_number): + return 3.0*baryon_number + 1.0*number_of_antiquarks diff --git a/root/organs10/physics/specialists/solved-number-of-quarks/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-number-of-quarks/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-number-of-quarks/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-object-distance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-object-distance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-object-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-object-distance/panel.json b/root/organs10/physics/specialists/solved-object-distance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..b4a389b50d8adb94eea63c01aaf33e9c258622fe --- /dev/null +++ b/root/organs10/physics/specialists/solved-object-distance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the object distance for focal length 8.50728 and image distance 17.7888?", + "a": "16.30493319026239", + "valid": true, + "kind": "compute", + "expect": 16.30493319026239, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [8.507283, 17.788778] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 8.50728 and image distance of 17.7888.", + "a": "16.30493319026239", + "valid": true, + "kind": "compute", + "expect": 16.30493319026239, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [8.507283, 17.788778] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 6.34623 and image distance 21.511?", + "a": "9.002020937156367", + "valid": true, + "kind": "compute", + "expect": 9.002020937156367, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [6.346226, 21.511016] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 6.34623 and image distance of 21.511.", + "a": "9.002020937156367", + "valid": true, + "kind": "compute", + "expect": 9.002020937156367, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [6.346226, 21.511016] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 1.64379 and image distance 252.709?", + "a": "1.6545578917201085", + "valid": true, + "kind": "compute", + "expect": 1.6545578917201085, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [1.643795, 252.709024] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 1.64379 and image distance of 252.709.", + "a": "1.6545578917201085", + "valid": true, + "kind": "compute", + "expect": 1.6545578917201085, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [1.643795, 252.709024] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 21.7931 and image distance 29.5106?", + "a": "83.33396999459883", + "valid": true, + "kind": "compute", + "expect": 83.33396999459883, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [21.793126, 29.510609] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 21.7931 and image distance of 29.5106.", + "a": "83.33396999459883", + "valid": true, + "kind": "compute", + "expect": 83.33396999459883, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [21.793126, 29.510609] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 7.10705 and image distance 30.2507?", + "a": "9.289506925951446", + "valid": true, + "kind": "compute", + "expect": 9.289506925951446, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [7.107049, 30.250749] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 7.10705 and image distance of 30.2507.", + "a": "9.289506925951446", + "valid": true, + "kind": "compute", + "expect": 9.289506925951446, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [7.107049, 30.250749] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 0.869111 and image distance 39.1753?", + "a": "0.888830328008647", + "valid": true, + "kind": "compute", + "expect": 0.888830328008647, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.869111, 39.175263] (the system Thin lens)" + }, + { + "q": "Tell me the object distance with focal length of 0.869111 and image distance of 39.1753.", + "a": "0.888830328008647", + "valid": true, + "kind": "compute", + "expect": 0.888830328008647, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.869111, 39.175263] (the system Thin lens)" + }, + { + "q": "What is the object distance for focal length 8.50728?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the image distance is not given" + }, + { + "q": "Tell me the object distance with focal length of 6.34623.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the image distance is not given" + }, + { + "q": "What is the object 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 object 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 object distance with focal length of -1.64379 and image distance of 252.709.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative focal length: no example had one" + }, + { + "q": "Which object 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 focal length is 169.527 and the image distance is 280.774, what is the object distance?", + "a": "427.8661070290953", + "valid": true, + "kind": "compute", + "expect": 427.8661070290953, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [169.526958, 280.773702] (the system Thin lens)" + }, + { + "q": "Could you work out the object distance given focal length = 169.527, image distance = 280.774?", + "a": "427.8661070290953", + "valid": true, + "kind": "compute", + "expect": 427.8661070290953, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [169.526958, 280.773702] (the system Thin lens)" + }, + { + "q": "I need the object distance for a focal length of 0.318734 and an image distance of 9.56607, please.", + "a": "0.32972006381830044", + "valid": true, + "kind": "compute", + "expect": 0.32972006381830044, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.318734, 9.566071] (the system Thin lens)" + }, + { + "q": "If the focal length is 0.318734 and the image distance is 9.56607, what is the object distance?", + "a": "0.32972006381830044", + "valid": true, + "kind": "compute", + "expect": 0.32972006381830044, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.318734, 9.566071] (the system Thin lens)" + }, + { + "q": "Could you work out the object distance given focal length = 0.671697, image distance = 14.2496?", + "a": "0.7049260536493527", + "valid": true, + "kind": "compute", + "expect": 0.7049260536493527, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.671697, 14.249569] (the system Thin lens)" + }, + { + "q": "I need the object distance for a focal length of 0.671697 and an image distance of 14.2496, please.", + "a": "0.7049260536493527", + "valid": true, + "kind": "compute", + "expect": 0.7049260536493527, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [0.671697, 14.249569] (the system Thin lens)" + }, + { + "q": "If the focal length is 156.502 and the image distance is 185.886, what is the object distance?", + "a": "990.031299651779", + "valid": true, + "kind": "compute", + "expect": 990.031299651779, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [156.50181, 185.886273] (the system Thin lens)" + }, + { + "q": "Could you work out the object distance given focal length = 156.502, image distance = 185.886?", + "a": "990.031299651779", + "valid": true, + "kind": "compute", + "expect": 990.031299651779, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [156.50181, 185.886273] (the system Thin lens)" + }, + { + "q": "I need the object distance for a focal length of 24.5721 and an image distance of 108.451, please.", + "a": "31.770425101524573", + "valid": true, + "kind": "compute", + "expect": 31.770425101524573, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [24.572086, 108.450792] (the system Thin lens)" + }, + { + "q": "If the focal length is 24.5721 and the image distance is 108.451, what is the object distance?", + "a": "31.770425101524573", + "valid": true, + "kind": "compute", + "expect": 31.770425101524573, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [24.572086, 108.450792] (the system Thin lens)" + }, + { + "q": "Could you work out the object distance given focal length = 4.07774, image distance = 276.408?", + "a": "4.138800977948351", + "valid": true, + "kind": "compute", + "expect": 4.138800977948351, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [4.077743, 276.407582] (the system Thin lens)" + }, + { + "q": "I need the object distance for a focal length of 4.07774 and an image distance of 276.408, please.", + "a": "4.138800977948351", + "valid": true, + "kind": "compute", + "expect": 4.138800977948351, + "dtype": "quantity", + "unit": "m", + "why": "object distance for [4.077743, 276.407582] (the system Thin lens)" + }, + { + "q": "If the focal length is 169.527, what is the object distance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the image distance is not given" + }, + { + "q": "Could you work out the object distance given focal length = 0.318734?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the image distance is not given" + }, + { + "q": "Do you know the object 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 object 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 object distance given focal length = -0.671697, image distance = 14.2496?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative focal length: no example had one" + }, + { + "q": "What is a typical object 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-object-distance/program.py b/root/organs10/physics/specialists/solved-object-distance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..9a6ee46e2c4e0512c98f43d2d3344a22296d2635 --- /dev/null +++ b/root/organs10/physics/specialists/solved-object-distance/program.py @@ -0,0 +1,7 @@ +"""object distance from focal length, image distance (Thin lens) +The maths organ (systems.py): solved from the system 1/f = 1/o + 1/i; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(focal_length, image_distance): + return -1.0*focal_length*image_distance/(focal_length - image_distance) diff --git a/root/organs10/physics/specialists/solved-object-distance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-object-distance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-object-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-observation-duration/organ_formula_v2.py b/root/organs10/physics/specialists/solved-observation-duration/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-observation-duration/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-observation-duration/panel.json b/root/organs10/physics/specialists/solved-observation-duration/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..6c488902e9b8c9988c6ceae5372e45d2b47621a6 --- /dev/null +++ b/root/organs10/physics/specialists/solved-observation-duration/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the observation duration for stress relaxation time 107.961 and Deborah number 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [107.960666, 59.4105] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 107.961 and Deborah number of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [107.960666, 59.4105] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 169.527 and Deborah number 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [169.526958, 280.773702] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 169.527 and Deborah number of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [169.526958, 280.773702] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 1.91195 and Deborah number 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [1.911952, 82.240072] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 1.91195 and Deborah number of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [1.911952, 82.240072] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 1.64379 and Deborah number 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [1.643795, 252.709024] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 1.64379 and Deborah number of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [1.643795, 252.709024] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 18.3169 and Deborah number 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [18.316867, 6.838598] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 18.3169 and Deborah number of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [18.316867, 6.838598] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 156.502 and Deborah number 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [156.50181, 185.886273] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 156.502 and Deborah number of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [156.50181, 185.886273] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "What is the observation duration for stress relaxation time 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Deborah number is not given" + }, + { + "q": "Tell me the observation duration with stress relaxation time of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Deborah number is not given" + }, + { + "q": "What is the observation duration 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 observation duration 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 observation duration with stress relaxation time of -1.91195 and Deborah number of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative stress relaxation time: no example had one" + }, + { + "q": "Which observation duration 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 stress relaxation time is 8.50728 and the Deborah number is 17.7888, what is the observation duration?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [8.507283, 17.788778] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Could you work out the observation duration given stress relaxation time = 8.50728, Deborah number = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [8.507283, 17.788778] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "I need the observation duration for a stress relaxation time of 8.24951 and a Deborah number of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [8.24951, 0.634021] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "If the stress relaxation time is 8.24951 and the Deborah number is 0.634021, what is the observation duration?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [8.24951, 0.634021] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Could you work out the observation duration given stress relaxation time = 0.318734, Deborah number = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [0.318734, 9.566071] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "I need the observation duration for a stress relaxation time of 0.318734 and a Deborah number of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [0.318734, 9.566071] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "If the stress relaxation time is 0.671697 and the Deborah number is 14.2496, what is the observation duration?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [0.671697, 14.249569] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Could you work out the observation duration given stress relaxation time = 0.671697, Deborah number = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [0.671697, 14.249569] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "I need the observation duration for a stress relaxation time of 21.7931 and a Deborah number of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [21.793126, 29.510609] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "If the stress relaxation time is 21.7931 and the Deborah number is 29.5106, what is the observation duration?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [21.793126, 29.510609] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "Could you work out the observation duration given stress relaxation time = 153.15, Deborah number = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [153.149965, 18.595315] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "I need the observation duration for a stress relaxation time of 153.15 and a Deborah number of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s", + "why": "observation duration for [153.149965, 18.595315] (the system Deborah number (Wikidata Q1138045))" + }, + { + "q": "If the stress relaxation time is 8.50728, what is the observation duration?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Deborah number is not given" + }, + { + "q": "Could you work out the observation duration given stress relaxation time = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the Deborah number is not given" + }, + { + "q": "Do you know the observation duration 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 observation duration 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 observation duration given stress relaxation time = -0.318734, Deborah number = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative stress relaxation time: no example had one" + }, + { + "q": "What is a typical observation duration?", + "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-observation-duration/program.py b/root/organs10/physics/specialists/solved-observation-duration/program.py new file mode 100644 index 0000000000000000000000000000000000000000..22312363476c4c1d99a1b6654e9d52f290f1fc71 --- /dev/null +++ b/root/organs10/physics/specialists/solved-observation-duration/program.py @@ -0,0 +1,7 @@ +"""observation duration from stress relaxation time, Deborah number (Deborah number (Wikidata Q1138045)) +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(stress_relaxation_time, deborah_number): + return 1.0*stress_relaxation_time/deborah_number diff --git a/root/organs10/physics/specialists/solved-observation-duration/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-observation-duration/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-observation-duration/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-orbit-radius/organ_formula_v2.py b/root/organs10/physics/specialists/solved-orbit-radius/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbit-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-orbit-radius/panel.json b/root/organs10/physics/specialists/solved-orbit-radius/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..fdaba44c3dd6298fdf9f7d293904bcc386b03da1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbit-radius/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the orbit radius for orbital speed 107.961 and body mass 59.4105?", + "a": "3.4020275270655837e-13", + "valid": true, + "kind": "compute", + "expect": 3.4020275270655837e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [107.960666, 59.4105] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 107.961 and body mass of 59.4105.", + "a": "3.4020275270655837e-13", + "valid": true, + "kind": "compute", + "expect": 3.4020275270655837e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [107.960666, 59.4105] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital speed 169.527 and body mass 280.774?", + "a": "6.520555803016851e-13", + "valid": true, + "kind": "compute", + "expect": 6.520555803016851e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [169.526958, 280.773702] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 169.527 and body mass of 280.774.", + "a": "6.520555803016851e-13", + "valid": true, + "kind": "compute", + "expect": 6.520555803016851e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [169.526958, 280.773702] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital speed 1.91195 and body mass 82.2401?", + "a": "1.5015345938010145e-09", + "valid": true, + "kind": "compute", + "expect": 1.5015345938010145e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [1.911952, 82.240072] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 1.91195 and body mass of 82.2401.", + "a": "1.5015345938010145e-09", + "valid": true, + "kind": "compute", + "expect": 1.5015345938010145e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [1.911952, 82.240072] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital speed 1.64379 and body mass 252.709?", + "a": "6.242102600728808e-09", + "valid": true, + "kind": "compute", + "expect": 6.242102600728808e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [1.643795, 252.709024] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 1.64379 and body mass of 252.709.", + "a": "6.242102600728808e-09", + "valid": true, + "kind": "compute", + "expect": 6.242102600728808e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [1.643795, 252.709024] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital speed 18.3169 and body mass 6.8386?", + "a": "1.3604118850526486e-12", + "valid": true, + "kind": "compute", + "expect": 1.3604118850526486e-12, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [18.316867, 6.838598] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 18.3169 and body mass of 6.8386.", + "a": "1.3604118850526486e-12", + "valid": true, + "kind": "compute", + "expect": 1.3604118850526486e-12, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [18.316867, 6.838598] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital speed 156.502 and body mass 185.886?", + "a": "5.065406635848351e-13", + "valid": true, + "kind": "compute", + "expect": 5.065406635848351e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [156.50181, 185.886273] (the system Orbital speed)" + }, + { + "q": "Tell me the orbit radius with orbital speed of 156.502 and body mass of 185.886.", + "a": "5.065406635848351e-13", + "valid": true, + "kind": "compute", + "expect": 5.065406635848351e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [156.50181, 185.886273] (the system Orbital speed)" + }, + { + "q": "What is the orbit radius for orbital 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 orbit radius with orbital 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 orbit 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 orbit 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 orbit radius with orbital 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 orbital speed: no example had one" + }, + { + "q": "Which orbit 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 orbital speed is 8.50728 and the body mass is 17.7888, what is the orbit radius?", + "a": "1.6404768915461017e-11", + "valid": true, + "kind": "compute", + "expect": 1.6404768915461017e-11, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [8.507283, 17.788778] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbit radius given orbital speed = 8.50728, body mass = 17.7888?", + "a": "1.6404768915461017e-11", + "valid": true, + "kind": "compute", + "expect": 1.6404768915461017e-11, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [8.507283, 17.788778] (the system Orbital speed)" + }, + { + "q": "I need the orbit radius for an orbital speed of 8.24951 and a body mass of 0.634021, please.", + "a": "6.218033466318201e-13", + "valid": true, + "kind": "compute", + "expect": 6.218033466318201e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [8.24951, 0.634021] (the system Orbital speed)" + }, + { + "q": "If the orbital speed is 8.24951 and the body mass is 0.634021, what is the orbit radius?", + "a": "6.218033466318201e-13", + "valid": true, + "kind": "compute", + "expect": 6.218033466318201e-13, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [8.24951, 0.634021] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbit radius given orbital speed = 0.318734, body mass = 9.56607?", + "a": "6.2846689695993846e-09", + "valid": true, + "kind": "compute", + "expect": 6.2846689695993846e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [0.318734, 9.566071] (the system Orbital speed)" + }, + { + "q": "I need the orbit radius for an orbital speed of 0.318734 and a body mass of 9.56607, please.", + "a": "6.2846689695993846e-09", + "valid": true, + "kind": "compute", + "expect": 6.2846689695993846e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [0.318734, 9.566071] (the system Orbital speed)" + }, + { + "q": "If the orbital speed is 0.671697 and the body mass is 14.2496, what is the orbit radius?", + "a": "2.107950393283379e-09", + "valid": true, + "kind": "compute", + "expect": 2.107950393283379e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [0.671697, 14.249569] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbit radius given orbital speed = 0.671697, body mass = 14.2496?", + "a": "2.107950393283379e-09", + "valid": true, + "kind": "compute", + "expect": 2.107950393283379e-09, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [0.671697, 14.249569] (the system Orbital speed)" + }, + { + "q": "I need the orbit radius for an orbital speed of 21.7931 and a body mass of 29.5106, please.", + "a": "4.1471028998519044e-12", + "valid": true, + "kind": "compute", + "expect": 4.1471028998519044e-12, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [21.793126, 29.510609] (the system Orbital speed)" + }, + { + "q": "If the orbital speed is 21.7931 and the body mass is 29.5106, what is the orbit radius?", + "a": "4.1471028998519044e-12", + "valid": true, + "kind": "compute", + "expect": 4.1471028998519044e-12, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [21.793126, 29.510609] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbit radius given orbital speed = 153.15, body mass = 18.5953?", + "a": "5.291459417607281e-14", + "valid": true, + "kind": "compute", + "expect": 5.291459417607281e-14, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [153.149965, 18.595315] (the system Orbital speed)" + }, + { + "q": "I need the orbit radius for an orbital speed of 153.15 and a body mass of 18.5953, please.", + "a": "5.291459417607281e-14", + "valid": true, + "kind": "compute", + "expect": 5.291459417607281e-14, + "dtype": "quantity", + "unit": "m", + "why": "orbit radius for [153.149965, 18.595315] (the system Orbital speed)" + }, + { + "q": "If the orbital speed is 8.50728, what is the orbit 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 orbit radius given orbital 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 orbit 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 orbit 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 orbit radius given orbital speed = -0.318734, body mass = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative orbital speed: no example had one" + }, + { + "q": "What is a typical orbit 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-orbit-radius/program.py b/root/organs10/physics/specialists/solved-orbit-radius/program.py new file mode 100644 index 0000000000000000000000000000000000000000..1028c86d4b5ae5b08069e2f118b23c1928b90b51 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbit-radius/program.py @@ -0,0 +1,7 @@ +"""orbit radius from orbital speed, body mass (Orbital speed) +The maths organ (systems.py): solved from the system v = sqrt(G*M/r); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(orbital_speed, body_mass): + return 6.67429999999999e-11*body_mass/orbital_speed**2 diff --git a/root/organs10/physics/specialists/solved-orbit-radius/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-orbit-radius/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbit-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-orbital-speed/organ_formula_v2.py b/root/organs10/physics/specialists/solved-orbital-speed/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbital-speed/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-orbital-speed/panel.json b/root/organs10/physics/specialists/solved-orbital-speed/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c58dfd06db2d466560d0ff508b519a450a57572a --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbital-speed/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the orbital speed for body mass 107.961 and orbit radius 59.4105?", + "a": "1.1012959312123481e-05", + "valid": true, + "kind": "compute", + "expect": 1.1012959312123481e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [107.960666, 59.4105] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 107.961 and orbit radius of 59.4105.", + "a": "1.1012959312123481e-05", + "valid": true, + "kind": "compute", + "expect": 1.1012959312123481e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [107.960666, 59.4105] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 169.527 and orbit radius 280.774?", + "a": "6.348103979605575e-06", + "valid": true, + "kind": "compute", + "expect": 6.348103979605575e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [169.526958, 280.773702] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 169.527 and orbit radius of 280.774.", + "a": "6.348103979605575e-06", + "valid": true, + "kind": "compute", + "expect": 6.348103979605575e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [169.526958, 280.773702] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 1.91195 and orbit radius 82.2401?", + "a": "1.245660195236173e-06", + "valid": true, + "kind": "compute", + "expect": 1.245660195236173e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [1.911952, 82.240072] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 1.91195 and orbit radius of 82.2401.", + "a": "1.245660195236173e-06", + "valid": true, + "kind": "compute", + "expect": 1.245660195236173e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [1.911952, 82.240072] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 1.64379 and orbit radius 252.709?", + "a": "6.588952539484249e-07", + "valid": true, + "kind": "compute", + "expect": 6.588952539484249e-07, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [1.643795, 252.709024] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 1.64379 and orbit radius of 252.709.", + "a": "6.588952539484249e-07", + "valid": true, + "kind": "compute", + "expect": 6.588952539484249e-07, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [1.643795, 252.709024] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 18.3169 and orbit radius 6.8386?", + "a": "1.3370415963038737e-05", + "valid": true, + "kind": "compute", + "expect": 1.3370415963038737e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [18.316867, 6.838598] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 18.3169 and orbit radius of 6.8386.", + "a": "1.3370415963038737e-05", + "valid": true, + "kind": "compute", + "expect": 1.3370415963038737e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [18.316867, 6.838598] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 156.502 and orbit radius 185.886?", + "a": "7.496160629349766e-06", + "valid": true, + "kind": "compute", + "expect": 7.496160629349766e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [156.50181, 185.886273] (the system Orbital speed)" + }, + { + "q": "Tell me the orbital speed with body mass of 156.502 and orbit radius of 185.886.", + "a": "7.496160629349766e-06", + "valid": true, + "kind": "compute", + "expect": 7.496160629349766e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [156.50181, 185.886273] (the system Orbital speed)" + }, + { + "q": "What is the orbital speed for body mass 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the orbit radius is not given" + }, + { + "q": "Tell me the orbital speed with body mass of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the orbit radius is not given" + }, + { + "q": "What is the orbital speed 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 orbital speed 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 orbital speed with body mass of -1.91195 and orbit radius of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative body mass: no example had one" + }, + { + "q": "Which orbital speed 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 body mass is 8.50728 and the orbit radius is 17.7888, what is the orbital speed?", + "a": "5.6496980038038605e-06", + "valid": true, + "kind": "compute", + "expect": 5.6496980038038605e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [8.507283, 17.788778] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbital speed given body mass = 8.50728, orbit radius = 17.7888?", + "a": "5.6496980038038605e-06", + "valid": true, + "kind": "compute", + "expect": 5.6496980038038605e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [8.507283, 17.788778] (the system Orbital speed)" + }, + { + "q": "I need the orbital speed for a body mass of 8.24951 and an orbit radius of 0.634021, please.", + "a": "2.946898128148863e-05", + "valid": true, + "kind": "compute", + "expect": 2.946898128148863e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [8.24951, 0.634021] (the system Orbital speed)" + }, + { + "q": "If the body mass is 8.24951 and the orbit radius is 0.634021, what is the orbital speed?", + "a": "2.946898128148863e-05", + "valid": true, + "kind": "compute", + "expect": 2.946898128148863e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [8.24951, 0.634021] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbital speed given body mass = 0.318734, orbit radius = 9.56607?", + "a": "1.491249431457296e-06", + "valid": true, + "kind": "compute", + "expect": 1.491249431457296e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [0.318734, 9.566071] (the system Orbital speed)" + }, + { + "q": "I need the orbital speed for a body mass of 0.318734 and an orbit radius of 9.56607, please.", + "a": "1.491249431457296e-06", + "valid": true, + "kind": "compute", + "expect": 1.491249431457296e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [0.318734, 9.566071] (the system Orbital speed)" + }, + { + "q": "If the body mass is 0.671697 and the orbit radius is 14.2496, what is the orbital speed?", + "a": "1.7737351054547093e-06", + "valid": true, + "kind": "compute", + "expect": 1.7737351054547093e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [0.671697, 14.249569] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbital speed given body mass = 0.671697, orbit radius = 14.2496?", + "a": "1.7737351054547093e-06", + "valid": true, + "kind": "compute", + "expect": 1.7737351054547093e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [0.671697, 14.249569] (the system Orbital speed)" + }, + { + "q": "I need the orbital speed for a body mass of 21.7931 and an orbit radius of 29.5106, please.", + "a": "7.0205889818630545e-06", + "valid": true, + "kind": "compute", + "expect": 7.0205889818630545e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [21.793126, 29.510609] (the system Orbital speed)" + }, + { + "q": "If the body mass is 21.7931 and the orbit radius is 29.5106, what is the orbital speed?", + "a": "7.0205889818630545e-06", + "valid": true, + "kind": "compute", + "expect": 7.0205889818630545e-06, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [21.793126, 29.510609] (the system Orbital speed)" + }, + { + "q": "Could you work out the orbital speed given body mass = 153.15, orbit radius = 18.5953?", + "a": "2.3445502089819882e-05", + "valid": true, + "kind": "compute", + "expect": 2.3445502089819882e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [153.149965, 18.595315] (the system Orbital speed)" + }, + { + "q": "I need the orbital speed for a body mass of 153.15 and an orbit radius of 18.5953, please.", + "a": "2.3445502089819882e-05", + "valid": true, + "kind": "compute", + "expect": 2.3445502089819882e-05, + "dtype": "quantity", + "unit": "m/s", + "why": "orbital speed for [153.149965, 18.595315] (the system Orbital speed)" + }, + { + "q": "If the body mass is 8.50728, what is the orbital speed?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the orbit radius is not given" + }, + { + "q": "Could you work out the orbital speed given body mass = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the orbit radius is not given" + }, + { + "q": "Do you know the orbital speed 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 orbital speed 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 orbital speed given body mass = -0.318734, orbit radius = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative body mass: no example had one" + }, + { + "q": "What is a typical orbital speed?", + "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-orbital-speed/program.py b/root/organs10/physics/specialists/solved-orbital-speed/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8e55aa76069896a228fe97ed270f8d1cbba4a934 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbital-speed/program.py @@ -0,0 +1,7 @@ +"""orbital speed from body mass, orbit radius (Orbital speed) +The maths organ (systems.py): solved from the system v = sqrt(G*M/r); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(body_mass, orbit_radius): + return 8.16963891490927e-6*body_mass**0.5*orbit_radius**(-0.5) diff --git a/root/organs10/physics/specialists/solved-orbital-speed/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-orbital-speed/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-orbital-speed/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-order-of-reflexion/organ_formula_v2.py b/root/organs10/physics/specialists/solved-order-of-reflexion/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-order-of-reflexion/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-order-of-reflexion/panel.json b/root/organs10/physics/specialists/solved-order-of-reflexion/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..28faff4c0d8fb14739a93e91f9312079c3771d5f --- /dev/null +++ b/root/organs10/physics/specialists/solved-order-of-reflexion/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the order of reflexion for Bragg angle 107.961, lattice plane spacing 59.4105 and electromagnetic wavelength 5.77717?", + "a": "18.743753221353238", + "valid": true, + "kind": "compute", + "expect": 18.743753221353238, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [107.960666, 59.4105, 5.777165] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 107.961, lattice plane spacing of 59.4105 and electromagnetic wavelength of 5.77717.", + "a": "18.743753221353238", + "valid": true, + "kind": "compute", + "expect": 18.743753221353238, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [107.960666, 59.4105, 5.777165] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 8.24951, lattice plane spacing 0.634021 and electromagnetic wavelength 6.34623?", + "a": "0.18438368211528366", + "valid": true, + "kind": "compute", + "expect": 0.18438368211528366, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [8.24951, 0.634021, 6.346226] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 8.24951, lattice plane spacing of 0.634021 and electromagnetic wavelength of 6.34623.", + "a": "0.18438368211528366", + "valid": true, + "kind": "compute", + "expect": 0.18438368211528366, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [8.24951, 0.634021, 6.346226] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 126.709, lattice plane spacing 1.70503 and electromagnetic wavelength 2.9896?", + "a": "0.9868818983632268", + "valid": true, + "kind": "compute", + "expect": 0.9868818983632268, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [126.709252, 1.705032, 2.9896] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 126.709, lattice plane spacing of 1.70503 and electromagnetic wavelength of 2.9896.", + "a": "0.9868818983632268", + "valid": true, + "kind": "compute", + "expect": 0.9868818983632268, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [126.709252, 1.705032, 2.9896] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 20.3966, lattice plane spacing 18.3169 and electromagnetic wavelength 6.8386?", + "a": "5.3553906488932235", + "valid": true, + "kind": "compute", + "expect": 5.3553906488932235, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [20.396558, 18.316867, 6.838598] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 20.3966, lattice plane spacing of 18.3169 and electromagnetic wavelength of 6.8386.", + "a": "5.3553906488932235", + "valid": true, + "kind": "compute", + "expect": 5.3553906488932235, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [20.396558, 18.316867, 6.838598] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 75.8534, lattice plane spacing 0.558623 and electromagnetic wavelength 21.7946?", + "a": "0.022537659048755532", + "valid": true, + "kind": "compute", + "expect": 0.022537659048755532, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [75.853435, 0.558623, 21.794621] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 75.8534, lattice plane spacing of 0.558623 and electromagnetic wavelength of 21.7946.", + "a": "0.022537659048755532", + "valid": true, + "kind": "compute", + "expect": 0.022537659048755532, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [75.853435, 0.558623, 21.794621] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 169.843, lattice plane spacing 12.6647 and electromagnetic wavelength 34.8151?", + "a": "0.14250696217206893", + "valid": true, + "kind": "compute", + "expect": 0.14250696217206893, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [169.843153, 12.664671, 34.81508] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 169.843, lattice plane spacing of 12.6647 and electromagnetic wavelength of 34.8151.", + "a": "0.14250696217206893", + "valid": true, + "kind": "compute", + "expect": 0.14250696217206893, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [169.843153, 12.664671, 34.81508] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "What is the order of reflexion for Bragg angle 107.961 and lattice plane spacing 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electromagnetic wavelength is not given" + }, + { + "q": "Tell me the order of reflexion with Bragg angle of 8.24951 and lattice plane spacing of 0.634021.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electromagnetic wavelength is not given" + }, + { + "q": "What is the order of reflexion 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 order of reflexion 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 order of reflexion with Bragg angle of -126.709, lattice plane spacing of 1.70503 and electromagnetic wavelength of 2.9896.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Bragg angle: no example had one" + }, + { + "q": "Which order of reflexion 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 Bragg angle is 2.21571, lattice plane spacing is 58.5346 and the electromagnetic wavelength is 22.652, what is the order of reflexion?", + "a": "4.130130746241888", + "valid": true, + "kind": "compute", + "expect": 4.130130746241888, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [2.215713, 58.534594, 22.652023] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Could you work out the order of reflexion given Bragg angle = 2.21571, lattice plane spacing = 58.5346, electromagnetic wavelength = 22.652?", + "a": "4.130130746241888", + "valid": true, + "kind": "compute", + "expect": 4.130130746241888, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [2.215713, 58.534594, 22.652023] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "I need the order of reflexion for a Bragg angle of 82.2401, a lattice plane spacing of 13.999 and an electromagnetic wavelength of 0.348438, please.", + "a": "42.59140360183006", + "valid": true, + "kind": "compute", + "expect": 42.59140360183006, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [82.240072, 13.999029, 0.348438] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "If the Bragg angle is 82.2401, lattice plane spacing is 13.999 and the electromagnetic wavelength is 0.348438, what is the order of reflexion?", + "a": "42.59140360183006", + "valid": true, + "kind": "compute", + "expect": 42.59140360183006, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [82.240072, 13.999029, 0.348438] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Could you work out the order of reflexion given Bragg angle = 6.98086, lattice plane spacing = 0.551236, electromagnetic wavelength = 2.88512?", + "a": "0.24548937883816757", + "valid": true, + "kind": "compute", + "expect": 0.24548937883816757, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [6.980857, 0.551236, 2.88512] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "I need the order of reflexion for a Bragg angle of 6.98086, a lattice plane spacing of 0.551236 and an electromagnetic wavelength of 2.88512, please.", + "a": "0.24548937883816757", + "valid": true, + "kind": "compute", + "expect": 0.24548937883816757, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [6.980857, 0.551236, 2.88512] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "If the Bragg angle is 21.7931, lattice plane spacing is 29.5106 and the electromagnetic wavelength is 8.50341, what is the order of reflexion?", + "a": "1.3654845118284265", + "valid": true, + "kind": "compute", + "expect": 1.3654845118284265, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [21.793126, 29.510609, 8.503407] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Could you work out the order of reflexion given Bragg angle = 21.7931, lattice plane spacing = 29.5106, electromagnetic wavelength = 8.50341?", + "a": "1.3654845118284265", + "valid": true, + "kind": "compute", + "expect": 1.3654845118284265, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [21.793126, 29.510609, 8.503407] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "I need the order of reflexion for a Bragg angle of 1.45005, a lattice plane spacing of 76.5154 and an electromagnetic wavelength of 3.14491, please.", + "a": "48.30549793767887", + "valid": true, + "kind": "compute", + "expect": 48.30549793767887, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [1.450045, 76.515411, 3.144912] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "If the Bragg angle is 1.45005, lattice plane spacing is 76.5154 and the electromagnetic wavelength is 3.14491, what is the order of reflexion?", + "a": "48.30549793767887", + "valid": true, + "kind": "compute", + "expect": 48.30549793767887, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [1.450045, 76.515411, 3.144912] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "Could you work out the order of reflexion given Bragg angle = 241.598, lattice plane spacing = 1.13479, electromagnetic wavelength = 0.744193?", + "a": "0.9139281955639208", + "valid": true, + "kind": "compute", + "expect": 0.9139281955639208, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [241.598281, 1.134791, 0.744193] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "I need the order of reflexion for a Bragg angle of 241.598, a lattice plane spacing of 1.13479 and an electromagnetic wavelength of 0.744193, please.", + "a": "0.9139281955639208", + "valid": true, + "kind": "compute", + "expect": 0.9139281955639208, + "dtype": "quantity", + "unit": "1", + "why": "order of reflexion for [241.598281, 1.134791, 0.744193] (the system Bragg angle (Wikidata Q105488118))" + }, + { + "q": "If the Bragg angle is 2.21571 and the lattice plane spacing is 58.5346, what is the order of reflexion?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electromagnetic wavelength is not given" + }, + { + "q": "Could you work out the order of reflexion given Bragg angle = 82.2401, lattice plane spacing = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electromagnetic wavelength is not given" + }, + { + "q": "Do you know the order of reflexion 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 order of reflexion 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 order of reflexion given Bragg angle = -6.98086, lattice plane spacing = 0.551236, electromagnetic wavelength = 2.88512?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Bragg angle: no example had one" + }, + { + "q": "What is a typical order of reflexion?", + "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-order-of-reflexion/program.py b/root/organs10/physics/specialists/solved-order-of-reflexion/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb980ed118239a20d4014748da637fe607f45c4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-order-of-reflexion/program.py @@ -0,0 +1,7 @@ +"""order of reflexion from Bragg angle, lattice plane spacing, electromagnetic wavelength (Bragg angle (Wikidata Q105488118)) +The maths organ (systems.py): solved from the system 2*q1*sin (q0) = q3*q2; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(bragg_angle, lattice_plane_spacing, electromagnetic_wavelength): + return 2.0*lattice_plane_spacing*math.sin(1.0*bragg_angle)/electromagnetic_wavelength diff --git a/root/organs10/physics/specialists/solved-order-of-reflexion/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-order-of-reflexion/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-order-of-reflexion/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-organ-dose/organ_formula_v2.py b/root/organs10/physics/specialists/solved-organ-dose/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-organ-dose/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-organ-dose/panel.json b/root/organs10/physics/specialists/solved-organ-dose/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..bab441ff5f9087fa8ee0afe21ad959235ac45666 --- /dev/null +++ b/root/organs10/physics/specialists/solved-organ-dose/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the organ dose for absorbed dose 107.961 and radiation weighting factor 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [107.960666, 59.4105] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 107.961 and radiation weighting factor of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [107.960666, 59.4105] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 169.527 and radiation weighting factor 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [169.526958, 280.773702] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 169.527 and radiation weighting factor of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [169.526958, 280.773702] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 1.91195 and radiation weighting factor 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [1.911952, 82.240072] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 1.91195 and radiation weighting factor of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [1.911952, 82.240072] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 1.64379 and radiation weighting factor 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [1.643795, 252.709024] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 1.64379 and radiation weighting factor of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [1.643795, 252.709024] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 18.3169 and radiation weighting factor 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [18.316867, 6.838598] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 18.3169 and radiation weighting factor of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [18.316867, 6.838598] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 156.502 and radiation weighting factor 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [156.50181, 185.886273] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Tell me the organ dose with absorbed dose of 156.502 and radiation weighting factor of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [156.50181, 185.886273] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "What is the organ dose for absorbed dose 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiation weighting factor is not given" + }, + { + "q": "Tell me the organ dose with absorbed dose of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiation weighting factor is not given" + }, + { + "q": "What is the organ dose 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 organ dose 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 organ dose with absorbed dose of -1.91195 and radiation weighting factor of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative absorbed dose: no example had one" + }, + { + "q": "Which organ dose 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 absorbed dose is 8.50728 and the radiation weighting factor is 17.7888, what is the organ dose?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [8.507283, 17.788778] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the organ dose given absorbed dose = 8.50728, radiation weighting factor = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [8.507283, 17.788778] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the organ dose for an absorbed dose of 8.24951 and a radiation weighting factor of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [8.24951, 0.634021] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the absorbed dose is 8.24951 and the radiation weighting factor is 0.634021, what is the organ dose?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [8.24951, 0.634021] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the organ dose given absorbed dose = 0.318734, radiation weighting factor = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [0.318734, 9.566071] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the organ dose for an absorbed dose of 0.318734 and a radiation weighting factor of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [0.318734, 9.566071] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the absorbed dose is 0.671697 and the radiation weighting factor is 14.2496, what is the organ dose?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [0.671697, 14.249569] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the organ dose given absorbed dose = 0.671697, radiation weighting factor = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [0.671697, 14.249569] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the organ dose for an absorbed dose of 21.7931 and a radiation weighting factor of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [21.793126, 29.510609] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the absorbed dose is 21.7931 and the radiation weighting factor is 29.5106, what is the organ dose?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [21.793126, 29.510609] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "Could you work out the organ dose given absorbed dose = 153.15, radiation weighting factor = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [153.149965, 18.595315] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "I need the organ dose for an absorbed dose of 153.15 and a radiation weighting factor of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m^2/s^2", + "why": "organ dose for [153.149965, 18.595315] (the system organ dose (Wikidata Q65242595))" + }, + { + "q": "If the absorbed dose is 8.50728, what is the organ dose?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiation weighting factor is not given" + }, + { + "q": "Could you work out the organ dose given absorbed dose = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the radiation weighting factor is not given" + }, + { + "q": "Do you know the organ dose 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 organ dose 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 organ dose given absorbed dose = -0.318734, radiation weighting factor = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative absorbed dose: no example had one" + }, + { + "q": "What is a typical organ dose?", + "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-organ-dose/program.py b/root/organs10/physics/specialists/solved-organ-dose/program.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5c148546ccc3ab353152fb5025487ffaf2a14c --- /dev/null +++ b/root/organs10/physics/specialists/solved-organ-dose/program.py @@ -0,0 +1,7 @@ +"""organ dose from absorbed dose, radiation weighting factor (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(absorbed_dose, radiation_weighting_factor): + return 1.0*absorbed_dose*radiation_weighting_factor diff --git a/root/organs10/physics/specialists/solved-organ-dose/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-organ-dose/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-organ-dose/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-output-power-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-output-power-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-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-output-power-2/panel.json b/root/organs10/physics/specialists/solved-output-power-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..9a81d1f7251d046022e12d2dc05276611d380937 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-power-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the output power for input power 107.961 and power efficiency 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "output power for [107.960666, 59.4105] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 107.961 and power efficiency of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "output power for [107.960666, 59.4105] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 169.527 and power efficiency 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "output power for [169.526958, 280.773702] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 169.527 and power efficiency of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "output power for [169.526958, 280.773702] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 1.91195 and power efficiency 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.911952, 82.240072] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 1.91195 and power efficiency of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.911952, 82.240072] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 1.64379 and power efficiency 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.643795, 252.709024] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 1.64379 and power efficiency of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.643795, 252.709024] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 18.3169 and power efficiency 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "output power for [18.316867, 6.838598] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 18.3169 and power efficiency of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "output power for [18.316867, 6.838598] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 156.502 and power efficiency 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "output power for [156.50181, 185.886273] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Tell me the output power with input power of 156.502 and power efficiency of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "output power for [156.50181, 185.886273] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "What is the output power for input power 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power efficiency is not given" + }, + { + "q": "Tell me the output power with input power of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power efficiency is not given" + }, + { + "q": "What is the output 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 output 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 output power with input power of -1.91195 and power efficiency of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative input power: no example had one" + }, + { + "q": "Which output 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 input power is 8.50728 and the power efficiency is 17.7888, what is the output power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.507283, 17.788778] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the output power given input power = 8.50728, power efficiency = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.507283, 17.788778] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the output power for an input power of 8.24951 and a power efficiency of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.24951, 0.634021] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the input power is 8.24951 and the power efficiency is 0.634021, what is the output power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.24951, 0.634021] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the output power given input power = 0.318734, power efficiency = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.318734, 9.566071] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the output power for an input power of 0.318734 and a power efficiency of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.318734, 9.566071] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the input power is 0.671697 and the power efficiency is 14.2496, what is the output power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.671697, 14.249569] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the output power given input power = 0.671697, power efficiency = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.671697, 14.249569] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the output power for an input power of 21.7931 and a power efficiency of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "output power for [21.793126, 29.510609] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the input power is 21.7931 and the power efficiency is 29.5106, what is the output power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "output power for [21.793126, 29.510609] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "Could you work out the output power given input power = 153.15, power efficiency = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "output power for [153.149965, 18.595315] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "I need the output power for an input power of 153.15 and a power efficiency of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "output power for [153.149965, 18.595315] (the system power efficiency (Wikidata Q11945244))" + }, + { + "q": "If the input power is 8.50728, what is the output power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power efficiency is not given" + }, + { + "q": "Could you work out the output power given input power = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the power efficiency is not given" + }, + { + "q": "Do you know the output 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 output 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 output power given input power = -0.318734, power efficiency = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative input power: no example had one" + }, + { + "q": "What is a typical output 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-output-power-2/program.py b/root/organs10/physics/specialists/solved-output-power-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ab024134512bb1d19e37eb4ab25d508a667b20 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-power-2/program.py @@ -0,0 +1,7 @@ +"""output power from input power, power efficiency (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(input_power, power_efficiency): + return 1.0*input_power*power_efficiency diff --git a/root/organs10/physics/specialists/solved-output-power-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-output-power-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-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-output-power/organ_formula_v2.py b/root/organs10/physics/specialists/solved-output-power/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-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-output-power/panel.json b/root/organs10/physics/specialists/solved-output-power/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..351f9d3552725a70a78bd852cfa4b811a2cdd92b --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-power/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the output power for efficiency 107.961 and input power 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "output power for [107.960666, 59.4105] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 107.961 and input power of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "W", + "why": "output power for [107.960666, 59.4105] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 169.527 and input power 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "output power for [169.526958, 280.773702] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 169.527 and input power of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "W", + "why": "output power for [169.526958, 280.773702] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 1.91195 and input power 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.911952, 82.240072] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 1.91195 and input power of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.911952, 82.240072] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 1.64379 and input power 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.643795, 252.709024] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 1.64379 and input power of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "W", + "why": "output power for [1.643795, 252.709024] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 18.3169 and input power 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "output power for [18.316867, 6.838598] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 18.3169 and input power of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "W", + "why": "output power for [18.316867, 6.838598] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 156.502 and input power 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "output power for [156.50181, 185.886273] (the system Efficiency)" + }, + { + "q": "Tell me the output power with efficiency of 156.502 and input power of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "W", + "why": "output power for [156.50181, 185.886273] (the system Efficiency)" + }, + { + "q": "What is the output power for efficiency 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "Tell me the output power with efficiency 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 output 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 output 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 output power with efficiency of -1.91195 and input power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative efficiency: no example had one" + }, + { + "q": "Which output 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 8.50728 and the input power is 17.7888, what is the output power?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.507283, 17.788778] (the system Efficiency)" + }, + { + "q": "Could you work out the output power given efficiency = 8.50728, input power = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.507283, 17.788778] (the system Efficiency)" + }, + { + "q": "I need the output power for an efficiency of 8.24951 and an input power of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.24951, 0.634021] (the system Efficiency)" + }, + { + "q": "If the efficiency is 8.24951 and the input power is 0.634021, what is the output power?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "W", + "why": "output power for [8.24951, 0.634021] (the system Efficiency)" + }, + { + "q": "Could you work out the output power given efficiency = 0.318734, input power = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.318734, 9.566071] (the system Efficiency)" + }, + { + "q": "I need the output power for an efficiency of 0.318734 and an input power of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.318734, 9.566071] (the system Efficiency)" + }, + { + "q": "If the efficiency is 0.671697 and the input power is 14.2496, what is the output power?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.671697, 14.249569] (the system Efficiency)" + }, + { + "q": "Could you work out the output power given efficiency = 0.671697, input power = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "W", + "why": "output power for [0.671697, 14.249569] (the system Efficiency)" + }, + { + "q": "I need the output power for an efficiency of 21.7931 and an input power of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "output power for [21.793126, 29.510609] (the system Efficiency)" + }, + { + "q": "If the efficiency is 21.7931 and the input power is 29.5106, what is the output power?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "W", + "why": "output power for [21.793126, 29.510609] (the system Efficiency)" + }, + { + "q": "Could you work out the output power given efficiency = 153.15, input power = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "output power for [153.149965, 18.595315] (the system Efficiency)" + }, + { + "q": "I need the output power for an efficiency of 153.15 and an input power of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "W", + "why": "output power for [153.149965, 18.595315] (the system Efficiency)" + }, + { + "q": "If the efficiency is 8.50728, what is the output power?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the input power is not given" + }, + { + "q": "Could you work out the output power given efficiency = 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 output 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 output 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 output power given efficiency = -0.318734, input power = 9.56607?", + "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 output 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-output-power/program.py b/root/organs10/physics/specialists/solved-output-power/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d352153c9c79f357247fa2dc5047381ea0425bb3 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-power/program.py @@ -0,0 +1,7 @@ +"""output power from efficiency, input power (Efficiency) +The maths organ (systems.py): solved from the system O = e*I; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(efficiency, input_power): + return 1.0*efficiency*input_power diff --git a/root/organs10/physics/specialists/solved-output-power/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-output-power/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-output-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-p-clet-number-for-heat-transf/organ_formula_v2.py b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/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-p-clet-number-for-heat-transf/panel.json b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c7ed511d42540a00bc362380e6a0e9bef963b1db --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Péclet number for heat transfer for speed 107.961, length 59.4105 and thermal diffusivity 5.77717?", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [107.960666, 59.4105, 5.777165] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 107.961, length of 59.4105 and thermal diffusivity of 5.77717.", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [107.960666, 59.4105, 5.777165] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 85.2416, length 160.878 and thermal diffusivity 2.69428?", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [85.241623, 160.878442, 2.69428] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 85.2416, length of 160.878 and thermal diffusivity of 2.69428.", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [85.241623, 160.878442, 2.69428] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 45.6157, length 4.97131 and thermal diffusivity 94.305?", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [45.61567, 4.971307, 94.305046] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 45.6157, length of 4.97131 and thermal diffusivity of 94.305.", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [45.61567, 4.971307, 94.305046] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 10.5638, length 198.839 and thermal diffusivity 0.671697?", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [10.563843, 198.838955, 0.671697] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 10.5638, length of 198.839 and thermal diffusivity of 0.671697.", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [10.563843, 198.838955, 0.671697] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 21.7931, length 29.5106 and thermal diffusivity 8.50341?", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [21.793126, 29.510609, 8.503407] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 21.7931, length of 29.5106 and thermal diffusivity of 8.50341.", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [21.793126, 29.510609, 8.503407] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 223.509, length 17.3414 and thermal diffusivity 7.10705?", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [223.508796, 17.341435, 7.107049] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 223.509, length of 17.3414 and thermal diffusivity of 7.10705.", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [223.508796, 17.341435, 7.107049] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "What is the Péclet number for heat transfer for speed 107.961 and length 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Tell me the Péclet number for heat transfer with speed of 85.2416 and length of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "What is the Péclet number for heat transfer 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 Péclet number for heat transfer 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 Péclet number for heat transfer with speed of -45.6157, length of 4.97131 and thermal diffusivity of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed: no example had one" + }, + { + "q": "Which Péclet number for heat transfer 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 is 17.7888, length is 167.625 and the thermal diffusivity is 10.3291, what is the Péclet number for heat transfer?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [17.788778, 167.624948, 10.329054] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Could you work out the Péclet number for heat transfer given speed = 17.7888, length = 167.625, thermal diffusivity = 10.3291?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [17.788778, 167.624948, 10.329054] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "I need the Péclet number for heat transfer for a speed of 21.511, a length of 173.394 and a thermal diffusivity of 251.084, please.", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [21.511016, 173.393638, 251.084037] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "If the speed is 21.511, length is 173.394 and the thermal diffusivity is 251.084, what is the Péclet number for heat transfer?", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [21.511016, 173.393638, 251.084037] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Could you work out the Péclet number for heat transfer given speed = 129.245, length = 1.18359, thermal diffusivity = 15.9416?", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [129.244984, 1.18359, 15.941612] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "I need the Péclet number for heat transfer for a speed of 129.245, a length of 1.18359 and a thermal diffusivity of 15.9416, please.", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [129.244984, 1.18359, 15.941612] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "If the speed is 20.3966, length is 18.3169 and the thermal diffusivity is 6.8386, what is the Péclet number for heat transfer?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [20.396558, 18.316867, 6.838598] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Could you work out the Péclet number for heat transfer given speed = 20.3966, length = 18.3169, thermal diffusivity = 6.8386?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [20.396558, 18.316867, 6.838598] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "I need the Péclet number for heat transfer for a speed of 185.886, a length of 13.2373 and a thermal diffusivity of 4.71941, please.", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [185.886273, 13.237311, 4.719415] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "If the speed is 185.886, length is 13.2373 and the thermal diffusivity is 4.71941, what is the Péclet number for heat transfer?", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [185.886273, 13.237311, 4.719415] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "Could you work out the Péclet number for heat transfer given speed = 9.1061, length = 24.5721, thermal diffusivity = 108.451?", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [9.106104, 24.572086, 108.450792] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "I need the Péclet number for heat transfer for a speed of 9.1061, a length of 24.5721 and a thermal diffusivity of 108.451, please.", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for heat transfer for [9.106104, 24.572086, 108.450792] (the system Péclet number for heat transfer (Wikidata Q899769))" + }, + { + "q": "If the speed is 17.7888 and the length is 167.625, what is the Péclet number for heat transfer?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Could you work out the Péclet number for heat transfer given speed = 21.511, length = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thermal diffusivity is not given" + }, + { + "q": "Do you know the Péclet number for heat transfer 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 Péclet number for heat transfer 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 Péclet number for heat transfer given speed = -129.245, length = 1.18359, thermal diffusivity = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed: no example had one" + }, + { + "q": "What is a typical Péclet number for heat transfer?", + "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-p-clet-number-for-heat-transf/program.py b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/program.py new file mode 100644 index 0000000000000000000000000000000000000000..a60875848a619f7d63fca5ee9e855d9843fffe79 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/program.py @@ -0,0 +1,7 @@ +"""Péclet number for heat transfer from speed, length, thermal diffusivity (Péclet number for heat transfer (Wikidata Q899769)) +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(speed, length, thermal_diffusivity): + return 1.0*length*speed/thermal_diffusivity diff --git a/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-heat-transf/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-p-clet-number-for-mass-transf/organ_formula_v2.py b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/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-p-clet-number-for-mass-transf/panel.json b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f78e3018f11f7beec4d33f229f267f6a0154a6ec --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the Péclet number for mass transfer for speed 107.961, characteristic length 59.4105 and mass diffusivity 5.77717?", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [107.960666, 59.4105, 5.777165] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 107.961, characteristic length of 59.4105 and mass diffusivity of 5.77717.", + "a": "1110.2327161569876", + "valid": true, + "kind": "compute", + "expect": 1110.2327161569876, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [107.960666, 59.4105, 5.777165] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 85.2416, characteristic length 160.878 and mass diffusivity 2.69428?", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [85.241623, 160.878442, 2.69428] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 85.2416, characteristic length of 160.878 and mass diffusivity of 2.69428.", + "a": "5089.871888725082", + "valid": true, + "kind": "compute", + "expect": 5089.871888725082, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [85.241623, 160.878442, 2.69428] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 45.6157, characteristic length 4.97131 and mass diffusivity 94.305?", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [45.61567, 4.971307, 94.305046] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 45.6157, characteristic length of 4.97131 and mass diffusivity of 94.305.", + "a": "2.404638268801381", + "valid": true, + "kind": "compute", + "expect": 2.404638268801381, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [45.61567, 4.971307, 94.305046] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 10.5638, characteristic length 198.839 and mass diffusivity 0.671697?", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [10.563843, 198.838955, 0.671697] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 10.5638, characteristic length of 198.839 and mass diffusivity of 0.671697.", + "a": "3127.1582727254026", + "valid": true, + "kind": "compute", + "expect": 3127.1582727254026, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [10.563843, 198.838955, 0.671697] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 21.7931, characteristic length 29.5106 and mass diffusivity 8.50341?", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [21.793126, 29.510609, 8.503407] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 21.7931, characteristic length of 29.5106 and mass diffusivity of 8.50341.", + "a": "75.6318512050043", + "valid": true, + "kind": "compute", + "expect": 75.6318512050043, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [21.793126, 29.510609, 8.503407] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 223.509, characteristic length 17.3414 and mass diffusivity 7.10705?", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [223.508796, 17.341435, 7.107049] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 223.509, characteristic length of 17.3414 and mass diffusivity of 7.10705.", + "a": "545.3688543410761", + "valid": true, + "kind": "compute", + "expect": 545.3688543410761, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [223.508796, 17.341435, 7.107049] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "What is the Péclet number for mass transfer for speed 107.961 and characteristic length 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Tell me the Péclet number for mass transfer with speed of 85.2416 and characteristic length of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "What is the Péclet number for mass transfer 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 Péclet number for mass transfer 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 Péclet number for mass transfer with speed of -45.6157, characteristic length of 4.97131 and mass diffusivity of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed: no example had one" + }, + { + "q": "Which Péclet number for mass transfer 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 is 17.7888, characteristic length is 167.625 and the mass diffusivity is 10.3291, what is the Péclet number for mass transfer?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [17.788778, 167.624948, 10.329054] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Could you work out the Péclet number for mass transfer given speed = 17.7888, characteristic length = 167.625, mass diffusivity = 10.3291?", + "a": "288.6849919329577", + "valid": true, + "kind": "compute", + "expect": 288.6849919329577, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [17.788778, 167.624948, 10.329054] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "I need the Péclet number for mass transfer for a speed of 21.511, a characteristic length of 173.394 and a mass diffusivity of 251.084, please.", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [21.511016, 173.393638, 251.084037] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "If the speed is 21.511, characteristic length is 173.394 and the mass diffusivity is 251.084, what is the Péclet number for mass transfer?", + "a": "14.855079375871984", + "valid": true, + "kind": "compute", + "expect": 14.855079375871984, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [21.511016, 173.393638, 251.084037] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Could you work out the Péclet number for mass transfer given speed = 129.245, characteristic length = 1.18359, mass diffusivity = 15.9416?", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [129.244984, 1.18359, 15.941612] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "I need the Péclet number for mass transfer for a speed of 129.245, a characteristic length of 1.18359 and a mass diffusivity of 15.9416, please.", + "a": "9.59583449816029", + "valid": true, + "kind": "compute", + "expect": 9.59583449816029, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [129.244984, 1.18359, 15.941612] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "If the speed is 20.3966, characteristic length is 18.3169 and the mass diffusivity is 6.8386, what is the Péclet number for mass transfer?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [20.396558, 18.316867, 6.838598] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Could you work out the Péclet number for mass transfer given speed = 20.3966, characteristic length = 18.3169, mass diffusivity = 6.8386?", + "a": "54.63123238944198", + "valid": true, + "kind": "compute", + "expect": 54.63123238944198, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [20.396558, 18.316867, 6.838598] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "I need the Péclet number for mass transfer for a speed of 185.886, a characteristic length of 13.2373 and a mass diffusivity of 4.71941, please.", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [185.886273, 13.237311, 4.719415] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "If the speed is 185.886, characteristic length is 13.2373 and the mass diffusivity is 4.71941, what is the Péclet number for mass transfer?", + "a": "521.3854934623429", + "valid": true, + "kind": "compute", + "expect": 521.3854934623429, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [185.886273, 13.237311, 4.719415] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "Could you work out the Péclet number for mass transfer given speed = 9.1061, characteristic length = 24.5721, mass diffusivity = 108.451?", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [9.106104, 24.572086, 108.450792] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "I need the Péclet number for mass transfer for a speed of 9.1061, a characteristic length of 24.5721 and a mass diffusivity of 108.451, please.", + "a": "2.0632027126358947", + "valid": true, + "kind": "compute", + "expect": 2.0632027126358947, + "dtype": "quantity", + "unit": "1", + "why": "Péclet number for mass transfer for [9.106104, 24.572086, 108.450792] (the system Péclet number for mass transfer (Wikidata Q104542217))" + }, + { + "q": "If the speed is 17.7888 and the characteristic length is 167.625, what is the Péclet number for mass transfer?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Could you work out the Péclet number for mass transfer given speed = 21.511, characteristic length = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the mass diffusivity is not given" + }, + { + "q": "Do you know the Péclet number for mass transfer 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 Péclet number for mass transfer 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 Péclet number for mass transfer given speed = -129.245, characteristic length = 1.18359, mass diffusivity = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative speed: no example had one" + }, + { + "q": "What is a typical Péclet number for mass transfer?", + "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-p-clet-number-for-mass-transf/program.py b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c86ea930c2ab38b36f0e51b91838509c5b7d57 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/program.py @@ -0,0 +1,7 @@ +"""Péclet number for mass transfer from speed, characteristic length, mass diffusivity (Péclet number for mass transfer (Wikidata Q104542217)) +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(speed, characteristic_length, mass_diffusivity): + return 1.0*characteristic_length*speed/mass_diffusivity diff --git a/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-p-clet-number-for-mass-transf/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-panel-area/organ_formula_v2.py b/root/organs10/physics/specialists/solved-panel-area/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-panel-area/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-panel-area/panel.json b/root/organs10/physics/specialists/solved-panel-area/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..769788237c5aee6c5ce809e2978f7cfa4bd34888 --- /dev/null +++ b/root/organs10/physics/specialists/solved-panel-area/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the panel area for power 107.961, irradiance 59.4105 and efficiency 5.77717?", + "a": "0.31454848897160476", + "valid": true, + "kind": "compute", + "expect": 0.31454848897160476, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [107.960666, 59.4105, 5.777165] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 107.961, irradiance of 59.4105 and efficiency of 5.77717.", + "a": "0.31454848897160476", + "valid": true, + "kind": "compute", + "expect": 0.31454848897160476, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [107.960666, 59.4105, 5.777165] (the system Solar power)" + }, + { + "q": "What is the panel area for power 85.2416, irradiance 160.878 and efficiency 2.69428?", + "a": "0.19665778745152376", + "valid": true, + "kind": "compute", + "expect": 0.19665778745152376, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [85.241623, 160.878442, 2.69428] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 85.2416, irradiance of 160.878 and efficiency of 2.69428.", + "a": "0.19665778745152376", + "valid": true, + "kind": "compute", + "expect": 0.19665778745152376, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [85.241623, 160.878442, 2.69428] (the system Solar power)" + }, + { + "q": "What is the panel area for power 45.6157, irradiance 4.97131 and efficiency 94.305?", + "a": "0.09729902784967777", + "valid": true, + "kind": "compute", + "expect": 0.09729902784967777, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [45.61567, 4.971307, 94.305046] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 45.6157, irradiance of 4.97131 and efficiency of 94.305.", + "a": "0.09729902784967777", + "valid": true, + "kind": "compute", + "expect": 0.09729902784967777, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [45.61567, 4.971307, 94.305046] (the system Solar power)" + }, + { + "q": "What is the panel area for power 10.5638, irradiance 198.839 and efficiency 0.671697?", + "a": "0.07909461512056756", + "valid": true, + "kind": "compute", + "expect": 0.07909461512056756, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [10.563843, 198.838955, 0.671697] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 10.5638, irradiance of 198.839 and efficiency of 0.671697.", + "a": "0.07909461512056756", + "valid": true, + "kind": "compute", + "expect": 0.07909461512056756, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [10.563843, 198.838955, 0.671697] (the system Solar power)" + }, + { + "q": "What is the panel area for power 21.7931, irradiance 29.5106 and efficiency 8.50341?", + "a": "0.08684571530973768", + "valid": true, + "kind": "compute", + "expect": 0.08684571530973768, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [21.793126, 29.510609, 8.503407] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 21.7931, irradiance of 29.5106 and efficiency of 8.50341.", + "a": "0.08684571530973768", + "valid": true, + "kind": "compute", + "expect": 0.08684571530973768, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [21.793126, 29.510609, 8.503407] (the system Solar power)" + }, + { + "q": "What is the panel area for power 223.509, irradiance 17.3414 and efficiency 7.10705?", + "a": "1.813511306470856", + "valid": true, + "kind": "compute", + "expect": 1.813511306470856, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [223.508796, 17.341435, 7.107049] (the system Solar power)" + }, + { + "q": "Tell me the panel area with power of 223.509, irradiance of 17.3414 and efficiency of 7.10705.", + "a": "1.813511306470856", + "valid": true, + "kind": "compute", + "expect": 1.813511306470856, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [223.508796, 17.341435, 7.107049] (the system Solar power)" + }, + { + "q": "What is the panel area for power 107.961 and irradiance 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Tell me the panel area with power of 85.2416 and irradiance of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "What is the panel area 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 panel area 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 panel area with power of -45.6157, irradiance of 4.97131 and efficiency of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative power: no example had one" + }, + { + "q": "Which panel area 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 17.7888, irradiance is 167.625 and the efficiency is 10.3291, what is the panel area?", + "a": "0.010274173498684694", + "valid": true, + "kind": "compute", + "expect": 0.010274173498684694, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [17.788778, 167.624948, 10.329054] (the system Solar power)" + }, + { + "q": "Could you work out the panel area given power = 17.7888, irradiance = 167.625, efficiency = 10.3291?", + "a": "0.010274173498684694", + "valid": true, + "kind": "compute", + "expect": 0.010274173498684694, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [17.788778, 167.624948, 10.329054] (the system Solar power)" + }, + { + "q": "I need the panel area for a power of 21.511, an irradiance of 173.394 and an efficiency of 251.084, please.", + "a": "0.000494092950151496", + "valid": true, + "kind": "compute", + "expect": 0.000494092950151496, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [21.511016, 173.393638, 251.084037] (the system Solar power)" + }, + { + "q": "If the power is 21.511, irradiance is 173.394 and the efficiency is 251.084, what is the panel area?", + "a": "0.000494092950151496", + "valid": true, + "kind": "compute", + "expect": 0.000494092950151496, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [21.511016, 173.393638, 251.084037] (the system Solar power)" + }, + { + "q": "Could you work out the panel area given power = 129.245, irradiance = 1.18359, efficiency = 15.9416?", + "a": "6.849836414751194", + "valid": true, + "kind": "compute", + "expect": 6.849836414751194, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [129.244984, 1.18359, 15.941612] (the system Solar power)" + }, + { + "q": "I need the panel area for a power of 129.245, an irradiance of 1.18359 and an efficiency of 15.9416, please.", + "a": "6.849836414751194", + "valid": true, + "kind": "compute", + "expect": 6.849836414751194, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [129.244984, 1.18359, 15.941612] (the system Solar power)" + }, + { + "q": "If the power is 20.3966, irradiance is 18.3169 and the efficiency is 6.8386, what is the panel area?", + "a": "0.16283157083473473", + "valid": true, + "kind": "compute", + "expect": 0.16283157083473473, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [20.396558, 18.316867, 6.838598] (the system Solar power)" + }, + { + "q": "Could you work out the panel area given power = 20.3966, irradiance = 18.3169, efficiency = 6.8386?", + "a": "0.16283157083473473", + "valid": true, + "kind": "compute", + "expect": 0.16283157083473473, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [20.396558, 18.316867, 6.838598] (the system Solar power)" + }, + { + "q": "I need the panel area for a power of 185.886, an irradiance of 13.2373 and an efficiency of 4.71941, please.", + "a": "2.975496158535072", + "valid": true, + "kind": "compute", + "expect": 2.975496158535072, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [185.886273, 13.237311, 4.719415] (the system Solar power)" + }, + { + "q": "If the power is 185.886, irradiance is 13.2373 and the efficiency is 4.71941, what is the panel area?", + "a": "2.975496158535072", + "valid": true, + "kind": "compute", + "expect": 2.975496158535072, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [185.886273, 13.237311, 4.719415] (the system Solar power)" + }, + { + "q": "Could you work out the panel area given power = 9.1061, irradiance = 24.5721, efficiency = 108.451?", + "a": "0.003417101331511669", + "valid": true, + "kind": "compute", + "expect": 0.003417101331511669, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [9.106104, 24.572086, 108.450792] (the system Solar power)" + }, + { + "q": "I need the panel area for a power of 9.1061, an irradiance of 24.5721 and an efficiency of 108.451, please.", + "a": "0.003417101331511669", + "valid": true, + "kind": "compute", + "expect": 0.003417101331511669, + "dtype": "quantity", + "unit": "m^2", + "why": "panel area for [9.106104, 24.572086, 108.450792] (the system Solar power)" + }, + { + "q": "If the power is 17.7888 and the irradiance is 167.625, what is the panel area?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Could you work out the panel area given power = 21.511, irradiance = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the efficiency is not given" + }, + { + "q": "Do you know the panel area 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 panel area 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 panel area given power = -129.245, irradiance = 1.18359, efficiency = 15.9416?", + "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 panel area?", + "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-panel-area/program.py b/root/organs10/physics/specialists/solved-panel-area/program.py new file mode 100644 index 0000000000000000000000000000000000000000..48030bb0e941246a2f6b021304d5f33479bd4ff5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-panel-area/program.py @@ -0,0 +1,7 @@ +"""panel area from power, irradiance, 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(power, irradiance, efficiency): + return 1.0*power/(efficiency*irradiance) diff --git a/root/organs10/physics/specialists/solved-panel-area/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-panel-area/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-panel-area/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-parallel-displacement/organ_formula_v2.py b/root/organs10/physics/specialists/solved-parallel-displacement/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-parallel-displacement/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-parallel-displacement/panel.json b/root/organs10/physics/specialists/solved-parallel-displacement/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0970772779d446e1dec35ad81bd4ea8308c5e175 --- /dev/null +++ b/root/organs10/physics/specialists/solved-parallel-displacement/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the parallel displacement for shear strain 107.961 and thickness 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [107.960666, 59.4105] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 107.961 and thickness of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [107.960666, 59.4105] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 169.527 and thickness 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [169.526958, 280.773702] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 169.527 and thickness of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [169.526958, 280.773702] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 1.91195 and thickness 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [1.911952, 82.240072] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 1.91195 and thickness of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [1.911952, 82.240072] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 1.64379 and thickness 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [1.643795, 252.709024] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 1.64379 and thickness of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [1.643795, 252.709024] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 18.3169 and thickness 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [18.316867, 6.838598] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 18.3169 and thickness of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [18.316867, 6.838598] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 156.502 and thickness 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [156.50181, 185.886273] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Tell me the parallel displacement with shear strain of 156.502 and thickness of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [156.50181, 185.886273] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "What is the parallel displacement for shear strain 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thickness is not given" + }, + { + "q": "Tell me the parallel displacement with shear strain of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thickness is not given" + }, + { + "q": "What is the parallel displacement 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 parallel displacement 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 parallel displacement with shear strain of -1.91195 and thickness of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative shear strain: no example had one" + }, + { + "q": "Which parallel displacement 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 is 8.50728 and the thickness is 17.7888, what is the parallel displacement?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [8.507283, 17.788778] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Could you work out the parallel displacement given shear strain = 8.50728, thickness = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [8.507283, 17.788778] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "I need the parallel displacement for a shear strain of 8.24951 and a thickness of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [8.24951, 0.634021] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "If the shear strain is 8.24951 and the thickness is 0.634021, what is the parallel displacement?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [8.24951, 0.634021] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Could you work out the parallel displacement given shear strain = 0.318734, thickness = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [0.318734, 9.566071] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "I need the parallel displacement for a shear strain of 0.318734 and a thickness of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [0.318734, 9.566071] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "If the shear strain is 0.671697 and the thickness is 14.2496, what is the parallel displacement?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [0.671697, 14.249569] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Could you work out the parallel displacement given shear strain = 0.671697, thickness = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [0.671697, 14.249569] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "I need the parallel displacement for a shear strain of 21.7931 and a thickness of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [21.793126, 29.510609] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "If the shear strain is 21.7931 and the thickness is 29.5106, what is the parallel displacement?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [21.793126, 29.510609] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "Could you work out the parallel displacement given shear strain = 153.15, thickness = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [153.149965, 18.595315] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "I need the parallel displacement for a shear strain of 153.15 and a thickness of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "m", + "why": "parallel displacement for [153.149965, 18.595315] (the system shear strain (Wikidata Q7561704))" + }, + { + "q": "If the shear strain is 8.50728, what is the parallel displacement?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thickness is not given" + }, + { + "q": "Could you work out the parallel displacement given shear strain = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the thickness is not given" + }, + { + "q": "Do you know the parallel displacement 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 parallel displacement 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 parallel displacement given shear strain = -0.318734, thickness = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative shear strain: no example had one" + }, + { + "q": "What is a typical parallel displacement?", + "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-parallel-displacement/program.py b/root/organs10/physics/specialists/solved-parallel-displacement/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d890fdf510dc218fd1ada57140577a37a92e629c --- /dev/null +++ b/root/organs10/physics/specialists/solved-parallel-displacement/program.py @@ -0,0 +1,7 @@ +"""parallel displacement from shear strain, thickness (shear strain (Wikidata Q7561704)) +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(shear_strain, thickness): + return 1.0*shear_strain*thickness diff --git a/root/organs10/physics/specialists/solved-parallel-displacement/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-parallel-displacement/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-parallel-displacement/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-partial-pressure/organ_formula_v2.py b/root/organs10/physics/specialists/solved-partial-pressure/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-partial-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-partial-pressure/panel.json b/root/organs10/physics/specialists/solved-partial-pressure/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..351583c86129f02a01c38236c435d71a08907624 --- /dev/null +++ b/root/organs10/physics/specialists/solved-partial-pressure/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the partial pressure for amount-of-substance fraction 107.961 and pressure 59.4105?", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [107.960666, 59.4105] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 107.961 and pressure of 59.4105.", + "a": "6413.997161494573", + "valid": true, + "kind": "compute", + "expect": 6413.997161494573, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [107.960666, 59.4105] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 169.527 and pressure 280.774?", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [169.526958, 280.773702] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 169.527 and pressure of 280.774.", + "a": "47598.71144694985", + "valid": true, + "kind": "compute", + "expect": 47598.71144694985, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [169.526958, 280.773702] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 1.91195 and pressure 82.2401?", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [1.911952, 82.240072] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 1.91195 and pressure of 82.2401.", + "a": "157.23905034769402", + "valid": true, + "kind": "compute", + "expect": 157.23905034769402, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [1.911952, 82.240072] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 1.64379 and pressure 252.709?", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [1.643795, 252.709024] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 1.64379 and pressure of 252.709.", + "a": "415.4019555725448", + "valid": true, + "kind": "compute", + "expect": 415.4019555725448, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [1.643795, 252.709024] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 18.3169 and pressure 6.8386?", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [18.316867, 6.838598] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 18.3169 and pressure of 6.8386.", + "a": "125.26169131331936", + "valid": true, + "kind": "compute", + "expect": 125.26169131331936, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [18.316867, 6.838598] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 156.502 and pressure 185.886?", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [156.50181, 185.886273] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 156.502 and pressure of 185.886.", + "a": "29091.53810517715", + "valid": true, + "kind": "compute", + "expect": 29091.53810517715, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [156.50181, 185.886273] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "What is the partial pressure for amount-of-substance fraction 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Tell me the partial pressure with amount-of-substance fraction of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "What is the partial 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 partial 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 partial pressure with amount-of-substance fraction of -1.91195 and pressure of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount-of-substance fraction: no example had one" + }, + { + "q": "Which partial 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 amount-of-substance fraction is 8.50728 and the pressure is 17.7888, what is the partial pressure?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [8.507283, 17.788778] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the partial pressure given amount-of-substance fraction = 8.50728, pressure = 17.7888?", + "a": "151.33416360087082", + "valid": true, + "kind": "compute", + "expect": 151.33416360087082, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [8.507283, 17.788778] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the partial pressure for an amount-of-substance fraction of 8.24951 and a pressure of 0.634021, please.", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [8.24951, 0.634021] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the amount-of-substance fraction is 8.24951 and the pressure is 0.634021, what is the partial pressure?", + "a": "5.230362271972724", + "valid": true, + "kind": "compute", + "expect": 5.230362271972724, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [8.24951, 0.634021] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the partial pressure given amount-of-substance fraction = 0.318734, pressure = 9.56607?", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [0.318734, 9.566071] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the partial pressure for an amount-of-substance fraction of 0.318734 and a pressure of 9.56607, please.", + "a": "3.0490325263462696", + "valid": true, + "kind": "compute", + "expect": 3.0490325263462696, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [0.318734, 9.566071] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the amount-of-substance fraction is 0.671697 and the pressure is 14.2496, what is the partial pressure?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [0.671697, 14.249569] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the partial pressure given amount-of-substance fraction = 0.671697, pressure = 14.2496?", + "a": "9.571395807788361", + "valid": true, + "kind": "compute", + "expect": 9.571395807788361, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [0.671697, 14.249569] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the partial pressure for an amount-of-substance fraction of 21.7931 and a pressure of 29.5106, please.", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [21.793126, 29.510609] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the amount-of-substance fraction is 21.7931 and the pressure is 29.5106, what is the partial pressure?", + "a": "643.1284273894521", + "valid": true, + "kind": "compute", + "expect": 643.1284273894521, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [21.793126, 29.510609] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "Could you work out the partial pressure given amount-of-substance fraction = 153.15, pressure = 18.5953?", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [153.149965, 18.595315] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "I need the partial pressure for an amount-of-substance fraction of 153.15 and a pressure of 18.5953, please.", + "a": "2847.871916067332", + "valid": true, + "kind": "compute", + "expect": 2847.871916067332, + "dtype": "quantity", + "unit": "Pa", + "why": "partial pressure for [153.149965, 18.595315] (the system partial pressure (Wikidata Q27165))" + }, + { + "q": "If the amount-of-substance fraction is 8.50728, what is the partial pressure?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Could you work out the partial pressure given amount-of-substance fraction = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pressure is not given" + }, + { + "q": "Do you know the partial 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 partial 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 partial pressure given amount-of-substance fraction = -0.318734, pressure = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative amount-of-substance fraction: no example had one" + }, + { + "q": "What is a typical partial 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-partial-pressure/program.py b/root/organs10/physics/specialists/solved-partial-pressure/program.py new file mode 100644 index 0000000000000000000000000000000000000000..35bdd4d8ae0b86333dd7625b1590713b3aa8bebf --- /dev/null +++ b/root/organs10/physics/specialists/solved-partial-pressure/program.py @@ -0,0 +1,7 @@ +"""partial pressure from amount-of-substance fraction, pressure (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(amount_of_substance_fraction, pressure): + return 1.0*amount_of_substance_fraction*pressure diff --git a/root/organs10/physics/specialists/solved-partial-pressure/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-partial-pressure/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-partial-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-particle-diameter/organ_formula_v2.py b/root/organs10/physics/specialists/solved-particle-diameter/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-diameter/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-particle-diameter/panel.json b/root/organs10/physics/specialists/solved-particle-diameter/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a0dec9c024928349aaa722724ad4815e20347a98 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-diameter/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the particle diameter for Stokes number for vibrating particles 107.961, kinematic viscosity 59.4105 and particle vibration frequency 5.77717?", + "a": "0.30863235725016924", + "valid": true, + "kind": "compute", + "expect": 0.30863235725016924, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [107.960666, 59.4105, 5.777165] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 107.961, kinematic viscosity of 59.4105 and particle vibration frequency of 5.77717.", + "a": "0.30863235725016924", + "valid": true, + "kind": "compute", + "expect": 0.30863235725016924, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [107.960666, 59.4105, 5.777165] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 85.2416, kinematic viscosity 160.878 and particle vibration frequency 2.69428?", + "a": "0.8369542474165902", + "valid": true, + "kind": "compute", + "expect": 0.8369542474165902, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [85.241623, 160.878442, 2.69428] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 85.2416, kinematic viscosity of 160.878 and particle vibration frequency of 2.69428.", + "a": "0.8369542474165902", + "valid": true, + "kind": "compute", + "expect": 0.8369542474165902, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [85.241623, 160.878442, 2.69428] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 45.6157, kinematic viscosity 4.97131 and particle vibration frequency 94.305?", + "a": "0.03399466908805601", + "valid": true, + "kind": "compute", + "expect": 0.03399466908805601, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [45.61567, 4.971307, 94.305046] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 45.6157, kinematic viscosity of 4.97131 and particle vibration frequency of 94.305.", + "a": "0.03399466908805601", + "valid": true, + "kind": "compute", + "expect": 0.03399466908805601, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [45.61567, 4.971307, 94.305046] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 10.5638, kinematic viscosity 198.839 and particle vibration frequency 0.671697?", + "a": "5.293622940013613", + "valid": true, + "kind": "compute", + "expect": 5.293622940013613, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [10.563843, 198.838955, 0.671697] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 10.5638, kinematic viscosity of 198.839 and particle vibration frequency of 0.671697.", + "a": "5.293622940013613", + "valid": true, + "kind": "compute", + "expect": 5.293622940013613, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [10.563843, 198.838955, 0.671697] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 21.7931, kinematic viscosity 29.5106 and particle vibration frequency 8.50341?", + "a": "0.3990550633573216", + "valid": true, + "kind": "compute", + "expect": 0.3990550633573216, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [21.793126, 29.510609, 8.503407] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 21.7931, kinematic viscosity of 29.5106 and particle vibration frequency of 8.50341.", + "a": "0.3990550633573216", + "valid": true, + "kind": "compute", + "expect": 0.3990550633573216, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [21.793126, 29.510609, 8.503407] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 223.509, kinematic viscosity 17.3414 and particle vibration frequency 7.10705?", + "a": "0.10448418183695314", + "valid": true, + "kind": "compute", + "expect": 0.10448418183695314, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [223.508796, 17.341435, 7.107049] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 223.509, kinematic viscosity of 17.3414 and particle vibration frequency of 7.10705.", + "a": "0.10448418183695314", + "valid": true, + "kind": "compute", + "expect": 0.10448418183695314, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [223.508796, 17.341435, 7.107049] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle diameter for Stokes number for vibrating particles 107.961 and kinematic viscosity 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle vibration frequency is not given" + }, + { + "q": "Tell me the particle diameter with Stokes number for vibrating particles of 85.2416 and kinematic viscosity of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle vibration frequency is not given" + }, + { + "q": "What is the particle diameter 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 particle diameter 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 particle diameter with Stokes number for vibrating particles of -45.6157, kinematic viscosity of 4.97131 and particle vibration frequency of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Stokes number for vibrating particles: no example had one" + }, + { + "q": "Which particle diameter 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 Stokes number for vibrating particles is 17.7888, kinematic viscosity is 167.625 and the particle vibration frequency is 10.3291, what is the particle diameter?", + "a": "0.9551376946179183", + "valid": true, + "kind": "compute", + "expect": 0.9551376946179183, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [17.788778, 167.624948, 10.329054] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle diameter given Stokes number for vibrating particles = 17.7888, kinematic viscosity = 167.625, particle vibration frequency = 10.3291?", + "a": "0.9551376946179183", + "valid": true, + "kind": "compute", + "expect": 0.9551376946179183, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [17.788778, 167.624948, 10.329054] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle diameter for a Stokes number for vibrating particles of 21.511, a kinematic viscosity of 173.394 and a particle vibration frequency of 251.084, please.", + "a": "0.1791746513383686", + "valid": true, + "kind": "compute", + "expect": 0.1791746513383686, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [21.511016, 173.393638, 251.084037] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 21.511, kinematic viscosity is 173.394 and the particle vibration frequency is 251.084, what is the particle diameter?", + "a": "0.1791746513383686", + "valid": true, + "kind": "compute", + "expect": 0.1791746513383686, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [21.511016, 173.393638, 251.084037] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle diameter given Stokes number for vibrating particles = 129.245, kinematic viscosity = 1.18359, particle vibration frequency = 15.9416?", + "a": "0.02396777274315165", + "valid": true, + "kind": "compute", + "expect": 0.02396777274315165, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [129.244984, 1.18359, 15.941612] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle diameter for a Stokes number for vibrating particles of 129.245, a kinematic viscosity of 1.18359 and a particle vibration frequency of 15.9416, please.", + "a": "0.02396777274315165", + "valid": true, + "kind": "compute", + "expect": 0.02396777274315165, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [129.244984, 1.18359, 15.941612] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 20.3966, kinematic viscosity is 18.3169 and the particle vibration frequency is 6.8386, what is the particle diameter?", + "a": "0.36237949455689833", + "valid": true, + "kind": "compute", + "expect": 0.36237949455689833, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [20.396558, 18.316867, 6.838598] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle diameter given Stokes number for vibrating particles = 20.3966, kinematic viscosity = 18.3169, particle vibration frequency = 6.8386?", + "a": "0.36237949455689833", + "valid": true, + "kind": "compute", + "expect": 0.36237949455689833, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [20.396558, 18.316867, 6.838598] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle diameter for a Stokes number for vibrating particles of 185.886, a kinematic viscosity of 13.2373 and a particle vibration frequency of 4.71941, please.", + "a": "0.12283783468380632", + "valid": true, + "kind": "compute", + "expect": 0.12283783468380632, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [185.886273, 13.237311, 4.719415] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 185.886, kinematic viscosity is 13.2373 and the particle vibration frequency is 4.71941, what is the particle diameter?", + "a": "0.12283783468380632", + "valid": true, + "kind": "compute", + "expect": 0.12283783468380632, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [185.886273, 13.237311, 4.719415] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle diameter given Stokes number for vibrating particles = 9.1061, kinematic viscosity = 24.5721, particle vibration frequency = 108.451?", + "a": "0.15773873155532747", + "valid": true, + "kind": "compute", + "expect": 0.15773873155532747, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [9.106104, 24.572086, 108.450792] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle diameter for a Stokes number for vibrating particles of 9.1061, a kinematic viscosity of 24.5721 and a particle vibration frequency of 108.451, please.", + "a": "0.15773873155532747", + "valid": true, + "kind": "compute", + "expect": 0.15773873155532747, + "dtype": "quantity", + "unit": "m", + "why": "particle diameter for [9.106104, 24.572086, 108.450792] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 17.7888 and the kinematic viscosity is 167.625, what is the particle diameter?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle vibration frequency is not given" + }, + { + "q": "Could you work out the particle diameter given Stokes number for vibrating particles = 21.511, kinematic viscosity = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle vibration frequency is not given" + }, + { + "q": "Do you know the particle diameter 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 particle diameter 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 particle diameter given Stokes number for vibrating particles = -129.245, kinematic viscosity = 1.18359, particle vibration frequency = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Stokes number for vibrating particles: no example had one" + }, + { + "q": "What is a typical particle diameter?", + "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-particle-diameter/program.py b/root/organs10/physics/specialists/solved-particle-diameter/program.py new file mode 100644 index 0000000000000000000000000000000000000000..57f4e54100815cfcfbed14b86326f8a0f15c3861 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-diameter/program.py @@ -0,0 +1,7 @@ +"""particle diameter from Stokes number for vibrating particles, kinematic viscosity, particle vibration frequency (Stokes number for vibrating particles (Wikidata Q103820258)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2 **(2)*q3)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(stokes_number_for_vibrating_particles, kinematic_viscosity, particle_vibration_frequency): + return 1.0*kinematic_viscosity**0.5*particle_vibration_frequency**(-0.5)*stokes_number_for_vibrating_particles**(-0.5) diff --git a/root/organs10/physics/specialists/solved-particle-diameter/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-particle-diameter/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-diameter/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-particle-vibration-frequency/organ_formula_v2.py b/root/organs10/physics/specialists/solved-particle-vibration-frequency/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-vibration-frequency/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-particle-vibration-frequency/panel.json b/root/organs10/physics/specialists/solved-particle-vibration-frequency/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..414f4d2c5db4acab565304660d583c910b37b6af --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-vibration-frequency/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 107.961, kinematic viscosity 59.4105 and particle diameter 5.77717?", + "a": "0.01648800723194124", + "valid": true, + "kind": "compute", + "expect": 0.01648800723194124, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [107.960666, 59.4105, 5.777165] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 107.961, kinematic viscosity of 59.4105 and particle diameter of 5.77717.", + "a": "0.01648800723194124", + "valid": true, + "kind": "compute", + "expect": 0.01648800723194124, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [107.960666, 59.4105, 5.777165] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 85.2416, kinematic viscosity 160.878 and particle diameter 2.69428?", + "a": "0.2599924445336141", + "valid": true, + "kind": "compute", + "expect": 0.2599924445336141, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [85.241623, 160.878442, 2.69428] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 85.2416, kinematic viscosity of 160.878 and particle diameter of 2.69428.", + "a": "0.2599924445336141", + "valid": true, + "kind": "compute", + "expect": 0.2599924445336141, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [85.241623, 160.878442, 2.69428] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 45.6157, kinematic viscosity 4.97131 and particle diameter 94.305?", + "a": "1.2254249108541966e-05", + "valid": true, + "kind": "compute", + "expect": 1.2254249108541966e-05, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [45.61567, 4.971307, 94.305046] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 45.6157, kinematic viscosity of 4.97131 and particle diameter of 94.305.", + "a": "1.2254249108541966e-05", + "valid": true, + "kind": "compute", + "expect": 1.2254249108541966e-05, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [45.61567, 4.971307, 94.305046] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 10.5638, kinematic viscosity 198.839 and particle diameter 0.671697?", + "a": "41.71886355879462", + "valid": true, + "kind": "compute", + "expect": 41.71886355879462, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [10.563843, 198.838955, 0.671697] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 10.5638, kinematic viscosity of 198.839 and particle diameter of 0.671697.", + "a": "41.71886355879462", + "valid": true, + "kind": "compute", + "expect": 41.71886355879462, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [10.563843, 198.838955, 0.671697] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 21.7931, kinematic viscosity 29.5106 and particle diameter 8.50341?", + "a": "0.018727192526259213", + "valid": true, + "kind": "compute", + "expect": 0.018727192526259213, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [21.793126, 29.510609, 8.503407] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 21.7931, kinematic viscosity of 29.5106 and particle diameter of 8.50341.", + "a": "0.018727192526259213", + "valid": true, + "kind": "compute", + "expect": 0.018727192526259213, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [21.793126, 29.510609, 8.503407] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 223.509, kinematic viscosity 17.3414 and particle diameter 7.10705?", + "a": "0.0015360727073213487", + "valid": true, + "kind": "compute", + "expect": 0.0015360727073213487, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [223.508796, 17.341435, 7.107049] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 223.509, kinematic viscosity of 17.3414 and particle diameter of 7.10705.", + "a": "0.0015360727073213487", + "valid": true, + "kind": "compute", + "expect": 0.0015360727073213487, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [223.508796, 17.341435, 7.107049] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "What is the particle vibration frequency for Stokes number for vibrating particles 107.961 and kinematic viscosity 59.4105?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle diameter is not given" + }, + { + "q": "Tell me the particle vibration frequency with Stokes number for vibrating particles of 85.2416 and kinematic viscosity of 160.878.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle diameter is not given" + }, + { + "q": "What is the particle vibration frequency 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 particle vibration frequency 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 particle vibration frequency with Stokes number for vibrating particles of -45.6157, kinematic viscosity of 4.97131 and particle diameter of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Stokes number for vibrating particles: no example had one" + }, + { + "q": "Which particle vibration frequency 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 Stokes number for vibrating particles is 17.7888, kinematic viscosity is 167.625 and the particle diameter is 10.3291, what is the particle vibration frequency?", + "a": "0.08832250994410355", + "valid": true, + "kind": "compute", + "expect": 0.08832250994410355, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [17.788778, 167.624948, 10.329054] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle vibration frequency given Stokes number for vibrating particles = 17.7888, kinematic viscosity = 167.625, particle diameter = 10.3291?", + "a": "0.08832250994410355", + "valid": true, + "kind": "compute", + "expect": 0.08832250994410355, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [17.788778, 167.624948, 10.329054] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle vibration frequency for a Stokes number for vibrating particles of 21.511, a kinematic viscosity of 173.394 and a particle diameter of 251.084, please.", + "a": "0.00012785980352953056", + "valid": true, + "kind": "compute", + "expect": 0.00012785980352953056, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [21.511016, 173.393638, 251.084037] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 21.511, kinematic viscosity is 173.394 and the particle diameter is 251.084, what is the particle vibration frequency?", + "a": "0.00012785980352953056", + "valid": true, + "kind": "compute", + "expect": 0.00012785980352953056, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [21.511016, 173.393638, 251.084037] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle vibration frequency given Stokes number for vibrating particles = 129.245, kinematic viscosity = 1.18359, particle diameter = 15.9416?", + "a": "3.603488450597973e-05", + "valid": true, + "kind": "compute", + "expect": 3.603488450597973e-05, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [129.244984, 1.18359, 15.941612] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle vibration frequency for a Stokes number for vibrating particles of 129.245, a kinematic viscosity of 1.18359 and a particle diameter of 15.9416, please.", + "a": "3.603488450597973e-05", + "valid": true, + "kind": "compute", + "expect": 3.603488450597973e-05, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [129.244984, 1.18359, 15.941612] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 20.3966, kinematic viscosity is 18.3169 and the particle diameter is 6.8386, what is the particle vibration frequency?", + "a": "0.0192026051093826", + "valid": true, + "kind": "compute", + "expect": 0.0192026051093826, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [20.396558, 18.316867, 6.838598] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle vibration frequency given Stokes number for vibrating particles = 20.3966, kinematic viscosity = 18.3169, particle diameter = 6.8386?", + "a": "0.0192026051093826", + "valid": true, + "kind": "compute", + "expect": 0.0192026051093826, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [20.396558, 18.316867, 6.838598] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle vibration frequency for a Stokes number for vibrating particles of 185.886, a kinematic viscosity of 13.2373 and a particle diameter of 4.71941, please.", + "a": "0.003197246745560669", + "valid": true, + "kind": "compute", + "expect": 0.003197246745560669, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [185.886273, 13.237311, 4.719415] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 185.886, kinematic viscosity is 13.2373 and the particle diameter is 4.71941, what is the particle vibration frequency?", + "a": "0.003197246745560669", + "valid": true, + "kind": "compute", + "expect": 0.003197246745560669, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [185.886273, 13.237311, 4.719415] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "Could you work out the particle vibration frequency given Stokes number for vibrating particles = 9.1061, kinematic viscosity = 24.5721, particle diameter = 108.451?", + "a": "0.0002294267015243671", + "valid": true, + "kind": "compute", + "expect": 0.0002294267015243671, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [9.106104, 24.572086, 108.450792] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "I need the particle vibration frequency for a Stokes number for vibrating particles of 9.1061, a kinematic viscosity of 24.5721 and a particle diameter of 108.451, please.", + "a": "0.0002294267015243671", + "valid": true, + "kind": "compute", + "expect": 0.0002294267015243671, + "dtype": "quantity", + "unit": "Hz", + "why": "particle vibration frequency for [9.106104, 24.572086, 108.450792] (the system Stokes number for vibrating particles (Wikidata Q103820258))" + }, + { + "q": "If the Stokes number for vibrating particles is 17.7888 and the kinematic viscosity is 167.625, what is the particle vibration frequency?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle diameter is not given" + }, + { + "q": "Could you work out the particle vibration frequency given Stokes number for vibrating particles = 21.511, kinematic viscosity = 173.394?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the particle diameter is not given" + }, + { + "q": "Do you know the particle vibration frequency 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 particle vibration frequency 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 particle vibration frequency given Stokes number for vibrating particles = -129.245, kinematic viscosity = 1.18359, particle diameter = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Stokes number for vibrating particles: no example had one" + }, + { + "q": "What is a typical particle vibration frequency?", + "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-particle-vibration-frequency/program.py b/root/organs10/physics/specialists/solved-particle-vibration-frequency/program.py new file mode 100644 index 0000000000000000000000000000000000000000..9e763057900efaa9ed4a3acd4b84e1c9de94ad4b --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-vibration-frequency/program.py @@ -0,0 +1,7 @@ +"""particle vibration frequency from Stokes number for vibrating particles, kinematic viscosity, particle diameter (Stokes number for vibrating particles (Wikidata Q103820258)) +The maths organ (systems.py): solved from the system q0 = ((q1)/(q2 **(2)*q3)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(stokes_number_for_vibrating_particles, kinematic_viscosity, particle_diameter): + return 1.0*kinematic_viscosity/(particle_diameter**2*stokes_number_for_vibrating_particles) diff --git a/root/organs10/physics/specialists/solved-particle-vibration-frequency/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-particle-vibration-frequency/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-particle-vibration-frequency/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-pendulum-length/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pendulum-length/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pendulum-length/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-pendulum-length/panel.json b/root/organs10/physics/specialists/solved-pendulum-length/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..c42ebb719ee43c1e1c358656024d763f00a54ce4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pendulum-length/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pendulum length for period 107.961?", + "a": "2895.289851139229", + "valid": true, + "kind": "compute", + "expect": 2895.289851139229, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [107.960666] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 107.961.", + "a": "2895.289851139229", + "valid": true, + "kind": "compute", + "expect": 2895.289851139229, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [107.960666] (the system Pendulum)" + }, + { + "q": "What is the pendulum length for period 22.652?", + "a": "127.46029488753219", + "valid": true, + "kind": "compute", + "expect": 127.46029488753219, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [22.652023] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 22.652.", + "a": "127.46029488753219", + "valid": true, + "kind": "compute", + "expect": 127.46029488753219, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [22.652023] (the system Pendulum)" + }, + { + "q": "What is the pendulum length for period 173.394?", + "a": "7468.394634867317", + "valid": true, + "kind": "compute", + "expect": 7468.394634867317, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [173.393638] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 173.394.", + "a": "7468.394634867317", + "valid": true, + "kind": "compute", + "expect": 7468.394634867317, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [173.393638] (the system Pendulum)" + }, + { + "q": "What is the pendulum length for period 126.709?", + "a": "3988.2060853234325", + "valid": true, + "kind": "compute", + "expect": 3988.2060853234325, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [126.709252] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 126.709.", + "a": "3988.2060853234325", + "valid": true, + "kind": "compute", + "expect": 3988.2060853234325, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [126.709252] (the system Pendulum)" + }, + { + "q": "What is the pendulum length for period 0.671697?", + "a": "0.11207481081728014", + "valid": true, + "kind": "compute", + "expect": 0.11207481081728014, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [0.671697] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 0.671697.", + "a": "0.11207481081728014", + "valid": true, + "kind": "compute", + "expect": 0.11207481081728014, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [0.671697] (the system Pendulum)" + }, + { + "q": "What is the pendulum length for period 1.16997?", + "a": "0.34002348181208963", + "valid": true, + "kind": "compute", + "expect": 0.34002348181208963, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [1.169968] (the system Pendulum)" + }, + { + "q": "Tell me the pendulum length with period of 1.16997.", + "a": "0.34002348181208963", + "valid": true, + "kind": "compute", + "expect": 0.34002348181208963, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [1.169968] (the system Pendulum)" + }, + { + "q": "What is the pendulum length?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the period is not given" + }, + { + "q": "Could you work out the pendulum length, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the period is not given" + }, + { + "q": "What is the pendulum length 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 pendulum length 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 pendulum length with period of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative period: no example had one" + }, + { + "q": "Which pendulum length 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 period is 2.57003, what is the pendulum length?", + "a": "1.640730666013915", + "valid": true, + "kind": "compute", + "expect": 1.640730666013915, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [2.57003] (the system Pendulum)" + }, + { + "q": "Could you work out the pendulum length given period = 2.57003?", + "a": "1.640730666013915", + "valid": true, + "kind": "compute", + "expect": 1.640730666013915, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [2.57003] (the system Pendulum)" + }, + { + "q": "I need the pendulum length for a period of 48.921, please.", + "a": "594.4994106494729", + "valid": true, + "kind": "compute", + "expect": 594.4994106494729, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [48.920991] (the system Pendulum)" + }, + { + "q": "If the period is 48.921, what is the pendulum length?", + "a": "594.4994106494729", + "valid": true, + "kind": "compute", + "expect": 594.4994106494729, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [48.920991] (the system Pendulum)" + }, + { + "q": "Could you work out the pendulum length given period = 0.348438?", + "a": "0.030158597407945804", + "valid": true, + "kind": "compute", + "expect": 0.030158597407945804, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [0.348438] (the system Pendulum)" + }, + { + "q": "I need the pendulum length for a period of 0.348438, please.", + "a": "0.030158597407945804", + "valid": true, + "kind": "compute", + "expect": 0.030158597407945804, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [0.348438] (the system Pendulum)" + }, + { + "q": "If the period is 252.709, what is the pendulum length?", + "a": "15863.625203246767", + "valid": true, + "kind": "compute", + "expect": 15863.625203246767, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [252.709024] (the system Pendulum)" + }, + { + "q": "Could you work out the pendulum length given period = 252.709?", + "a": "15863.625203246767", + "valid": true, + "kind": "compute", + "expect": 15863.625203246767, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [252.709024] (the system Pendulum)" + }, + { + "q": "I need the pendulum length for a period of 20.3966, please.", + "a": "103.34148705476277", + "valid": true, + "kind": "compute", + "expect": 103.34148705476277, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [20.396558] (the system Pendulum)" + }, + { + "q": "If the period is 20.3966, what is the pendulum length?", + "a": "103.34148705476277", + "valid": true, + "kind": "compute", + "expect": 103.34148705476277, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [20.396558] (the system Pendulum)" + }, + { + "q": "Could you work out the pendulum length given period = 134.993?", + "a": "4526.715119164541", + "valid": true, + "kind": "compute", + "expect": 4526.715119164541, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [134.992958] (the system Pendulum)" + }, + { + "q": "I need the pendulum length for a period of 134.993, please.", + "a": "4526.715119164541", + "valid": true, + "kind": "compute", + "expect": 4526.715119164541, + "dtype": "quantity", + "unit": "m", + "why": "pendulum length for [134.992958] (the system Pendulum)" + }, + { + "q": "I need the pendulum length, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the period is not given" + }, + { + "q": "Can you tell me the pendulum length?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the period is not given" + }, + { + "q": "Do you know the pendulum length 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 pendulum length 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 pendulum length given period = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative period: no example had one" + }, + { + "q": "What is a typical pendulum length?", + "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-pendulum-length/program.py b/root/organs10/physics/specialists/solved-pendulum-length/program.py new file mode 100644 index 0000000000000000000000000000000000000000..916b60af39defbe6efdbe4e4a9a6e1ea17ecbb4c --- /dev/null +++ b/root/organs10/physics/specialists/solved-pendulum-length/program.py @@ -0,0 +1,7 @@ +"""pendulum length from period (Pendulum) +The maths organ (systems.py): solved from the system T = 2*q*sqrt(l/g); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(period): + return 0.248405346391533*period**2 diff --git a/root/organs10/physics/specialists/solved-pendulum-length/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pendulum-length/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pendulum-length/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-period-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-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-period-2/panel.json b/root/organs10/physics/specialists/solved-period-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..5494db6eaa7388f0bc13cbf0cc60001b19354a2e --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period for pendulum length 107.961?", + "a": "20.84741961161207", + "valid": true, + "kind": "compute", + "expect": 20.84741961161207, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 107.961.", + "a": "20.84741961161207", + "valid": true, + "kind": "compute", + "expect": 20.84741961161207, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system Pendulum)" + }, + { + "q": "What is the period for pendulum length 22.652?", + "a": "9.549332724224014", + "valid": true, + "kind": "compute", + "expect": 9.549332724224014, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 22.652.", + "a": "9.549332724224014", + "valid": true, + "kind": "compute", + "expect": 9.549332724224014, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system Pendulum)" + }, + { + "q": "What is the period for pendulum length 173.394?", + "a": "26.420200580434923", + "valid": true, + "kind": "compute", + "expect": 26.420200580434923, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 173.394.", + "a": "26.420200580434923", + "valid": true, + "kind": "compute", + "expect": 26.420200580434923, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system Pendulum)" + }, + { + "q": "What is the period for pendulum length 126.709?", + "a": "22.585187158139234", + "valid": true, + "kind": "compute", + "expect": 22.585187158139234, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 126.709.", + "a": "22.585187158139234", + "valid": true, + "kind": "compute", + "expect": 22.585187158139234, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system Pendulum)" + }, + { + "q": "What is the period for pendulum length 0.671697?", + "a": "1.6443955750931942", + "valid": true, + "kind": "compute", + "expect": 1.6443955750931942, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 0.671697.", + "a": "1.6443955750931942", + "valid": true, + "kind": "compute", + "expect": 1.6443955750931942, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system Pendulum)" + }, + { + "q": "What is the period for pendulum length 1.16997?", + "a": "2.1702338017238647", + "valid": true, + "kind": "compute", + "expect": 2.1702338017238647, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system Pendulum)" + }, + { + "q": "Tell me the period with pendulum length of 1.16997.", + "a": "2.1702338017238647", + "valid": true, + "kind": "compute", + "expect": 2.1702338017238647, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system Pendulum)" + }, + { + "q": "What is the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pendulum length is not given" + }, + { + "q": "Could you work out the period, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pendulum length is not given" + }, + { + "q": "What is the period 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 period 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 period with pendulum length of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative pendulum length: no example had one" + }, + { + "q": "Which period 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 pendulum length is 2.57003, what is the period?", + "a": "3.2165375051850575", + "valid": true, + "kind": "compute", + "expect": 3.2165375051850575, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system Pendulum)" + }, + { + "q": "Could you work out the period given pendulum length = 2.57003?", + "a": "3.2165375051850575", + "valid": true, + "kind": "compute", + "expect": 3.2165375051850575, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system Pendulum)" + }, + { + "q": "I need the period for a pendulum length of 48.921, please.", + "a": "14.03353728906728", + "valid": true, + "kind": "compute", + "expect": 14.03353728906728, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system Pendulum)" + }, + { + "q": "If the pendulum length is 48.921, what is the period?", + "a": "14.03353728906728", + "valid": true, + "kind": "compute", + "expect": 14.03353728906728, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system Pendulum)" + }, + { + "q": "Could you work out the period given pendulum length = 0.348438?", + "a": "1.1843554989516174", + "valid": true, + "kind": "compute", + "expect": 1.1843554989516174, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system Pendulum)" + }, + { + "q": "I need the period for a pendulum length of 0.348438, please.", + "a": "1.1843554989516174", + "valid": true, + "kind": "compute", + "expect": 1.1843554989516174, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system Pendulum)" + }, + { + "q": "If the pendulum length is 252.709, what is the period?", + "a": "31.89553608806881", + "valid": true, + "kind": "compute", + "expect": 31.89553608806881, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system Pendulum)" + }, + { + "q": "Could you work out the period given pendulum length = 252.709?", + "a": "31.89553608806881", + "valid": true, + "kind": "compute", + "expect": 31.89553608806881, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system Pendulum)" + }, + { + "q": "I need the period for a pendulum length of 20.3966, please.", + "a": "9.06145571913535", + "valid": true, + "kind": "compute", + "expect": 9.06145571913535, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system Pendulum)" + }, + { + "q": "If the pendulum length is 20.3966, what is the period?", + "a": "9.06145571913535", + "valid": true, + "kind": "compute", + "expect": 9.06145571913535, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system Pendulum)" + }, + { + "q": "Could you work out the period given pendulum length = 134.993?", + "a": "23.311761262360402", + "valid": true, + "kind": "compute", + "expect": 23.311761262360402, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system Pendulum)" + }, + { + "q": "I need the period for a pendulum length of 134.993, please.", + "a": "23.311761262360402", + "valid": true, + "kind": "compute", + "expect": 23.311761262360402, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system Pendulum)" + }, + { + "q": "I need the period, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pendulum length is not given" + }, + { + "q": "Can you tell me the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the pendulum length is not given" + }, + { + "q": "Do you know the period 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 period 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 period given pendulum length = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative pendulum length: no example had one" + }, + { + "q": "What is a typical period?", + "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-period-2/program.py b/root/organs10/physics/specialists/solved-period-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b90228c3251dc699e58f22147e48793c125c40 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-2/program.py @@ -0,0 +1,7 @@ +"""period from pendulum length (Pendulum) +The maths organ (systems.py): solved from the system T = 2*q*sqrt(l/g); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(pendulum_length): + return 2.00640929258904*pendulum_length**0.5 diff --git a/root/organs10/physics/specialists/solved-period-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-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-period-3/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period-3/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-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-period-3/panel.json b/root/organs10/physics/specialists/solved-period-3/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..06878649b1335e855ffaa32d93ed9302c0f84694 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-3/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period for light frequency 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period for light frequency 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period for light frequency 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period for light frequency 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period for light frequency 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period for light frequency 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Tell me the period with light frequency of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "What is the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Could you work out the period, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "What is the period 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 period 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 period with light frequency of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative light frequency: no example had one" + }, + { + "q": "Which period 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 light frequency is 2.57003, what is the period?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Could you work out the period given light frequency = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "I need the period for a light frequency of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "If the light frequency is 48.921, what is the period?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Could you work out the period given light frequency = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "I need the period for a light frequency of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "If the light frequency is 252.709, what is the period?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Could you work out the period given light frequency = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "I need the period for a light frequency of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "If the light frequency is 20.3966, what is the period?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "Could you work out the period given light frequency = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "I need the period for a light frequency of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system light frequency (Wikidata Q106008771))" + }, + { + "q": "I need the period, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Can you tell me the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Do you know the period 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 period 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 period given light frequency = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative light frequency: no example had one" + }, + { + "q": "What is a typical period?", + "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-period-3/program.py b/root/organs10/physics/specialists/solved-period-3/program.py new file mode 100644 index 0000000000000000000000000000000000000000..31e9eda24d4f92679f95feca7c90a0a576506c68 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-3/program.py @@ -0,0 +1,7 @@ +"""period from light frequency (light frequency (Wikidata Q106008771)) +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(light_frequency): + return 1.0/light_frequency diff --git a/root/organs10/physics/specialists/solved-period-3/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period-3/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-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-period-of-binary-digits-2/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits-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-period-of-binary-digits-2/panel.json b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7a55022da7fdcd049e14d7dffd825cb03bedb9c5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period of binary digits for signal energy per binary digit 107.961 and carrier power 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [107.960666, 59.4105] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 107.961 and carrier power of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [107.960666, 59.4105] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 169.527 and carrier power 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [169.526958, 280.773702] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 169.527 and carrier power of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [169.526958, 280.773702] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 1.91195 and carrier power 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.911952, 82.240072] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 1.91195 and carrier power of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.911952, 82.240072] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 1.64379 and carrier power 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.643795, 252.709024] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 1.64379 and carrier power of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.643795, 252.709024] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 18.3169 and carrier power 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [18.316867, 6.838598] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 18.3169 and carrier power of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [18.316867, 6.838598] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 156.502 and carrier power 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [156.50181, 185.886273] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 156.502 and carrier power of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [156.50181, 185.886273] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "What is the period of binary digits for signal energy per binary digit 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the carrier power is not given" + }, + { + "q": "Tell me the period of binary digits with signal energy per binary digit of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the carrier power is not given" + }, + { + "q": "What is the period of binary digits 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 period of binary digits 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 period of binary digits with signal energy per binary digit of -1.91195 and carrier power of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative signal energy per binary digit: no example had one" + }, + { + "q": "Which period of binary digits 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 energy per binary digit is 8.50728 and the carrier power is 17.7888, what is the period of binary digits?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [8.507283, 17.788778] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Could you work out the period of binary digits given signal energy per binary digit = 8.50728, carrier power = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [8.507283, 17.788778] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "I need the period of binary digits for a signal energy per binary digit of 8.24951 and a carrier power of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [8.24951, 0.634021] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "If the signal energy per binary digit is 8.24951 and the carrier power is 0.634021, what is the period of binary digits?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [8.24951, 0.634021] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Could you work out the period of binary digits given signal energy per binary digit = 0.318734, carrier power = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.318734, 9.566071] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "I need the period of binary digits for a signal energy per binary digit of 0.318734 and a carrier power of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.318734, 9.566071] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "If the signal energy per binary digit is 0.671697 and the carrier power is 14.2496, what is the period of binary digits?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.671697, 14.249569] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Could you work out the period of binary digits given signal energy per binary digit = 0.671697, carrier power = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.671697, 14.249569] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "I need the period of binary digits for a signal energy per binary digit of 21.7931 and a carrier power of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [21.793126, 29.510609] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "If the signal energy per binary digit is 21.7931 and the carrier power is 29.5106, what is the period of binary digits?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [21.793126, 29.510609] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "Could you work out the period of binary digits given signal energy per binary digit = 153.15, carrier power = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [153.149965, 18.595315] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "I need the period of binary digits for a signal energy per binary digit of 153.15 and a carrier power of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [153.149965, 18.595315] (the system signal energy per binary digit (Wikidata Q106344792))" + }, + { + "q": "If the signal energy per binary digit is 8.50728, what is the period of binary digits?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the carrier power is not given" + }, + { + "q": "Could you work out the period of binary digits given signal energy per binary digit = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the carrier power is not given" + }, + { + "q": "Do you know the period of binary digits 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 period of binary digits 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 period of binary digits given signal energy per binary digit = -0.318734, carrier power = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative signal energy per binary digit: no example had one" + }, + { + "q": "What is a typical period of binary digits?", + "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-period-of-binary-digits-2/program.py b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3506ce1b764725810b007b1fb11c466dc9358265 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/program.py @@ -0,0 +1,7 @@ +"""period of binary digits from signal energy per binary digit, carrier power (signal energy per binary digit (Wikidata Q106344792)) +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(signal_energy_per_binary_digit, carrier_power): + return 1.0*signal_energy_per_binary_digit/carrier_power diff --git a/root/organs10/physics/specialists/solved-period-of-binary-digits-2/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period-of-binary-digits-2/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits-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-period-of-binary-digits/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period-of-binary-digits/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits/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-period-of-binary-digits/panel.json b/root/organs10/physics/specialists/solved-period-of-binary-digits/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..323c42d3db22560fffb82bd9a443751609836d71 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period of binary digits for bit rate 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [107.960666] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [107.960666] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits for bit rate 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [22.652023] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [22.652023] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits for bit rate 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [173.393638] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [173.393638] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits for bit rate 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [126.709252] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [126.709252] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits for bit rate 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.671697] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.671697] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits for bit rate 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.169968] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Tell me the period of binary digits with bit rate of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [1.169968] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "What is the period of binary digits?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the bit rate is not given" + }, + { + "q": "Could you work out the period of binary digits, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the bit rate is not given" + }, + { + "q": "What is the period of binary digits 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 period of binary digits 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 period of binary digits with bit rate of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative bit rate: no example had one" + }, + { + "q": "Which period of binary digits 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 bit rate is 2.57003, what is the period of binary digits?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [2.57003] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Could you work out the period of binary digits given bit rate = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [2.57003] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "I need the period of binary digits for a bit rate of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [48.920991] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "If the bit rate is 48.921, what is the period of binary digits?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [48.920991] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Could you work out the period of binary digits given bit rate = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.348438] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "I need the period of binary digits for a bit rate of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [0.348438] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "If the bit rate is 252.709, what is the period of binary digits?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [252.709024] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Could you work out the period of binary digits given bit rate = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [252.709024] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "I need the period of binary digits for a bit rate of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [20.396558] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "If the bit rate is 20.3966, what is the period of binary digits?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [20.396558] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "Could you work out the period of binary digits given bit rate = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [134.992958] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "I need the period of binary digits for a bit rate of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period of binary digits for [134.992958] (the system period of binary digits (Wikidata Q106282183))" + }, + { + "q": "I need the period of binary digits, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the bit rate is not given" + }, + { + "q": "Can you tell me the period of binary digits?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the bit rate is not given" + }, + { + "q": "Do you know the period of binary digits 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 period of binary digits 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 period of binary digits given bit rate = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative bit rate: no example had one" + }, + { + "q": "What is a typical period of binary digits?", + "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-period-of-binary-digits/program.py b/root/organs10/physics/specialists/solved-period-of-binary-digits/program.py new file mode 100644 index 0000000000000000000000000000000000000000..85794f9b6645fbd90aedcb889f4e111674ea70e5 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits/program.py @@ -0,0 +1,7 @@ +"""period of binary digits from bit rate (period of binary digits (Wikidata Q106282183)) +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(bit_rate): + return 1.0/bit_rate diff --git a/root/organs10/physics/specialists/solved-period-of-binary-digits/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period-of-binary-digits/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-binary-digits/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-period-of-data-elements/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period-of-data-elements/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-data-elements/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-period-of-data-elements/panel.json b/root/organs10/physics/specialists/solved-period-of-data-elements/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..da60712672ae6386e3f67f49b4a9167c3987ff37 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-data-elements/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period of data elements for data transfer rate 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [107.960666] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [107.960666] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements for data transfer rate 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [22.652023] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [22.652023] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements for data transfer rate 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [173.393638] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [173.393638] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements for data transfer rate 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [126.709252] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [126.709252] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements for data transfer rate 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [0.671697] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [0.671697] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements for data transfer rate 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [1.169968] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Tell me the period of data elements with data transfer rate of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [1.169968] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "What is the period of data elements?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the data transfer rate is not given" + }, + { + "q": "Could you work out the period of data elements, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the data transfer rate is not given" + }, + { + "q": "What is the period of data elements 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 period of data elements 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 period of data elements with data transfer rate of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative data transfer rate: no example had one" + }, + { + "q": "Which period of data elements 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 data transfer rate is 2.57003, what is the period of data elements?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [2.57003] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Could you work out the period of data elements given data transfer rate = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [2.57003] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "I need the period of data elements for a data transfer rate of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [48.920991] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "If the data transfer rate is 48.921, what is the period of data elements?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [48.920991] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Could you work out the period of data elements given data transfer rate = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [0.348438] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "I need the period of data elements for a data transfer rate of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [0.348438] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "If the data transfer rate is 252.709, what is the period of data elements?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [252.709024] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Could you work out the period of data elements given data transfer rate = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [252.709024] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "I need the period of data elements for a data transfer rate of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [20.396558] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "If the data transfer rate is 20.3966, what is the period of data elements?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [20.396558] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "Could you work out the period of data elements given data transfer rate = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [134.992958] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "I need the period of data elements for a data transfer rate of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period of data elements for [134.992958] (the system period of data elements (Wikidata Q106268500))" + }, + { + "q": "I need the period of data elements, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the data transfer rate is not given" + }, + { + "q": "Can you tell me the period of data elements?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the data transfer rate is not given" + }, + { + "q": "Do you know the period of data elements 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 period of data elements 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 period of data elements given data transfer rate = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative data transfer rate: no example had one" + }, + { + "q": "What is a typical period of data elements?", + "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-period-of-data-elements/program.py b/root/organs10/physics/specialists/solved-period-of-data-elements/program.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2671ab595ce2f339938f6f088108c5e352f520 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-data-elements/program.py @@ -0,0 +1,7 @@ +"""period of data elements from data transfer rate (period of data elements (Wikidata Q106268500)) +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(data_transfer_rate): + return 1.0/data_transfer_rate diff --git a/root/organs10/physics/specialists/solved-period-of-data-elements/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period-of-data-elements/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period-of-data-elements/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-period/organ_formula_v2.py b/root/organs10/physics/specialists/solved-period/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period/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-period/panel.json b/root/organs10/physics/specialists/solved-period/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..2d9d9d56bae237e4601ed88eb6c7aa0375aaa6f6 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the period for frequency 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "s", + "why": "period for [107.960666] (the system Period)" + }, + { + "q": "What is the period for frequency 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "s", + "why": "period for [22.652023] (the system Period)" + }, + { + "q": "What is the period for frequency 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "s", + "why": "period for [173.393638] (the system Period)" + }, + { + "q": "What is the period for frequency 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "s", + "why": "period for [126.709252] (the system Period)" + }, + { + "q": "What is the period for frequency 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.671697] (the system Period)" + }, + { + "q": "What is the period for frequency 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system Period)" + }, + { + "q": "Tell me the period with frequency of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "s", + "why": "period for [1.169968] (the system Period)" + }, + { + "q": "What is the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the frequency is not given" + }, + { + "q": "Could you work out the period, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the frequency is not given" + }, + { + "q": "What is the period 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 period 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 period with frequency of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative frequency: no example had one" + }, + { + "q": "Which period 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 frequency is 2.57003, what is the period?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system Period)" + }, + { + "q": "Could you work out the period given frequency = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "s", + "why": "period for [2.57003] (the system Period)" + }, + { + "q": "I need the period for a frequency of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system Period)" + }, + { + "q": "If the frequency is 48.921, what is the period?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "s", + "why": "period for [48.920991] (the system Period)" + }, + { + "q": "Could you work out the period given frequency = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system Period)" + }, + { + "q": "I need the period for a frequency of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "s", + "why": "period for [0.348438] (the system Period)" + }, + { + "q": "If the frequency is 252.709, what is the period?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system Period)" + }, + { + "q": "Could you work out the period given frequency = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "s", + "why": "period for [252.709024] (the system Period)" + }, + { + "q": "I need the period for a frequency of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system Period)" + }, + { + "q": "If the frequency is 20.3966, what is the period?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "s", + "why": "period for [20.396558] (the system Period)" + }, + { + "q": "Could you work out the period given frequency = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system Period)" + }, + { + "q": "I need the period for a frequency of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "s", + "why": "period for [134.992958] (the system Period)" + }, + { + "q": "I need the period, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the frequency is not given" + }, + { + "q": "Can you tell me the period?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the frequency is not given" + }, + { + "q": "Do you know the period 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 period 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 period given frequency = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative frequency: no example had one" + }, + { + "q": "What is a typical period?", + "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-period/program.py b/root/organs10/physics/specialists/solved-period/program.py new file mode 100644 index 0000000000000000000000000000000000000000..50cf2c88a1010507e775d42782edbe0eb4bedd03 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period/program.py @@ -0,0 +1,7 @@ +"""period from frequency (Period) +The maths organ (systems.py): solved from the system T = 1/f; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(frequency): + return 1.0/frequency diff --git a/root/organs10/physics/specialists/solved-period/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-period/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-period/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-permeability-tensor/organ_formula_v2.py b/root/organs10/physics/specialists/solved-permeability-tensor/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability-tensor/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-permeability-tensor/panel.json b/root/organs10/physics/specialists/solved-permeability-tensor/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..015aba3920ff17453980b8c73a290300727d58f4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability-tensor/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the permeability tensor for magnetic flux density 107.961 and magnetic field strength 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [107.960666, 59.4105] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 107.961 and magnetic field strength of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [107.960666, 59.4105] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 169.527 and magnetic field strength 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [169.526958, 280.773702] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 169.527 and magnetic field strength of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [169.526958, 280.773702] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 1.91195 and magnetic field strength 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [1.911952, 82.240072] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 1.91195 and magnetic field strength of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [1.911952, 82.240072] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 1.64379 and magnetic field strength 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [1.643795, 252.709024] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 1.64379 and magnetic field strength of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [1.643795, 252.709024] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 18.3169 and magnetic field strength 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [18.316867, 6.838598] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 18.3169 and magnetic field strength of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [18.316867, 6.838598] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 156.502 and magnetic field strength 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [156.50181, 185.886273] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Tell me the permeability tensor with magnetic flux density of 156.502 and magnetic field strength of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [156.50181, 185.886273] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "What is the permeability tensor for magnetic flux density 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 permeability tensor with magnetic flux density 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 permeability tensor 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 permeability tensor 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 permeability tensor with magnetic flux density 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 magnetic flux density: no example had one" + }, + { + "q": "Which permeability tensor 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 flux density is 8.50728 and the magnetic field strength is 17.7888, what is the permeability tensor?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [8.507283, 17.788778] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Could you work out the permeability tensor given magnetic flux density = 8.50728, magnetic field strength = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [8.507283, 17.788778] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "I need the permeability tensor for a magnetic flux density of 8.24951 and a magnetic field strength of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [8.24951, 0.634021] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "If the magnetic flux density is 8.24951 and the magnetic field strength is 0.634021, what is the permeability tensor?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [8.24951, 0.634021] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Could you work out the permeability tensor given magnetic flux density = 0.318734, magnetic field strength = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [0.318734, 9.566071] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "I need the permeability tensor for a magnetic flux density of 0.318734 and a magnetic field strength of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [0.318734, 9.566071] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "If the magnetic flux density is 0.671697 and the magnetic field strength is 14.2496, what is the permeability tensor?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [0.671697, 14.249569] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Could you work out the permeability tensor given magnetic flux density = 0.671697, magnetic field strength = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [0.671697, 14.249569] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "I need the permeability tensor for a magnetic flux density of 21.7931 and a magnetic field strength of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [21.793126, 29.510609] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "If the magnetic flux density is 21.7931 and the magnetic field strength is 29.5106, what is the permeability tensor?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [21.793126, 29.510609] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "Could you work out the permeability tensor given magnetic flux density = 153.15, magnetic field strength = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [153.149965, 18.595315] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "I need the permeability tensor for a magnetic flux density of 153.15 and a magnetic field strength of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m*kg/s^2/A^2", + "why": "permeability tensor for [153.149965, 18.595315] (the system permeability tensor (Wikidata Q118895841))" + }, + { + "q": "If the magnetic flux density is 8.50728, what is the permeability tensor?", + "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 permeability tensor given magnetic flux density = 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 permeability tensor 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 permeability tensor 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 permeability tensor given magnetic flux density = -0.318734, magnetic field strength = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic flux density: no example had one" + }, + { + "q": "What is a typical permeability tensor?", + "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-permeability-tensor/program.py b/root/organs10/physics/specialists/solved-permeability-tensor/program.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c93cd38f0b17beee309786d14f0b7294ae4b50 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability-tensor/program.py @@ -0,0 +1,7 @@ +"""permeability tensor from magnetic flux density, magnetic field strength (permeability tensor (Wikidata Q118895841)) +The maths organ (systems.py): solved from the system q2 = q1 * q3; checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(magnetic_flux_density, magnetic_field_strength): + return 1.0*magnetic_flux_density/magnetic_field_strength diff --git a/root/organs10/physics/specialists/solved-permeability-tensor/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-permeability-tensor/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability-tensor/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-permeability/organ_formula_v2.py b/root/organs10/physics/specialists/solved-permeability/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability/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-permeability/panel.json b/root/organs10/physics/specialists/solved-permeability/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..baebd2f98a3153e6160ad86af9731087720e8403 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the permeability for Darcy number 107.961 and characteristic length 59.4105?", + "a": "381058.77958914574", + "valid": true, + "kind": "compute", + "expect": 381058.77958914574, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [107.960666, 59.4105] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 107.961 and characteristic length of 59.4105.", + "a": "381058.77958914574", + "valid": true, + "kind": "compute", + "expect": 381058.77958914574, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [107.960666, 59.4105] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 169.527 and characteristic length 280.774?", + "a": "13364466.42057454", + "valid": true, + "kind": "compute", + "expect": 13364466.42057454, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [169.526958, 280.773702] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 169.527 and characteristic length of 280.774.", + "a": "13364466.42057454", + "valid": true, + "kind": "compute", + "expect": 13364466.42057454, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [169.526958, 280.773702] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 1.91195 and characteristic length 82.2401?", + "a": "12931.350797066336", + "valid": true, + "kind": "compute", + "expect": 12931.350797066336, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [1.911952, 82.240072] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 1.91195 and characteristic length of 82.2401.", + "a": "12931.350797066336", + "valid": true, + "kind": "compute", + "expect": 12931.350797066336, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [1.911952, 82.240072] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 1.64379 and characteristic length 252.709?", + "a": "104975.82286408338", + "valid": true, + "kind": "compute", + "expect": 104975.82286408338, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [1.643795, 252.709024] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 1.64379 and characteristic length of 252.709.", + "a": "104975.82286408338", + "valid": true, + "kind": "compute", + "expect": 104975.82286408338, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [1.643795, 252.709024] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 18.3169 and characteristic length 6.8386?", + "a": "856.6143593859481", + "valid": true, + "kind": "compute", + "expect": 856.6143593859481, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [18.316867, 6.838598] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 18.3169 and characteristic length of 6.8386.", + "a": "856.6143593859481", + "valid": true, + "kind": "compute", + "expect": 856.6143593859481, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [18.316867, 6.838598] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 156.502 and characteristic length 185.886?", + "a": "5407717.588152708", + "valid": true, + "kind": "compute", + "expect": 5407717.588152708, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [156.50181, 185.886273] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Tell me the permeability with Darcy number of 156.502 and characteristic length of 185.886.", + "a": "5407717.588152708", + "valid": true, + "kind": "compute", + "expect": 5407717.588152708, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [156.50181, 185.886273] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "What is the permeability for Darcy number 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the characteristic length is not given" + }, + { + "q": "Tell me the permeability with Darcy number of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the characteristic length is not given" + }, + { + "q": "What is the permeability 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 permeability 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 permeability with Darcy number of -1.91195 and characteristic length of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Darcy number: no example had one" + }, + { + "q": "Which permeability 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 Darcy number is 8.50728 and the characteristic length is 17.7888, what is the permeability?", + "a": "2692.0498594103697", + "valid": true, + "kind": "compute", + "expect": 2692.0498594103697, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [8.507283, 17.788778] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Could you work out the permeability given Darcy number = 8.50728, characteristic length = 17.7888?", + "a": "2692.0498594103697", + "valid": true, + "kind": "compute", + "expect": 2692.0498594103697, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [8.507283, 17.788778] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "I need the permeability for a Darcy number of 8.24951 and a characteristic length of 0.634021, please.", + "a": "3.3161593761140393", + "valid": true, + "kind": "compute", + "expect": 3.3161593761140393, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [8.24951, 0.634021] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "If the Darcy number is 8.24951 and the characteristic length is 0.634021, what is the permeability?", + "a": "3.3161593761140393", + "valid": true, + "kind": "compute", + "expect": 3.3161593761140393, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [8.24951, 0.634021] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Could you work out the permeability given Darcy number = 0.318734, characteristic length = 9.56607?", + "a": "29.16726159383275", + "valid": true, + "kind": "compute", + "expect": 29.16726159383275, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [0.318734, 9.566071] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "I need the permeability for a Darcy number of 0.318734 and a characteristic length of 9.56607, please.", + "a": "29.16726159383275", + "valid": true, + "kind": "compute", + "expect": 29.16726159383275, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [0.318734, 9.566071] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "If the Darcy number is 0.671697 and the characteristic length is 14.2496, what is the permeability?", + "a": "136.38826801335216", + "valid": true, + "kind": "compute", + "expect": 136.38826801335216, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [0.671697, 14.249569] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Could you work out the permeability given Darcy number = 0.671697, characteristic length = 14.2496?", + "a": "136.38826801335216", + "valid": true, + "kind": "compute", + "expect": 136.38826801335216, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [0.671697, 14.249569] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "I need the permeability for a Darcy number of 21.7931 and a characteristic length of 29.5106, please.", + "a": "18979.11133874426", + "valid": true, + "kind": "compute", + "expect": 18979.11133874426, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [21.793126, 29.510609] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "If the Darcy number is 21.7931 and the characteristic length is 29.5106, what is the permeability?", + "a": "18979.11133874426", + "valid": true, + "kind": "compute", + "expect": 18979.11133874426, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [21.793126, 29.510609] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "Could you work out the permeability given Darcy number = 153.15, characteristic length = 18.5953?", + "a": "52957.07669974909", + "valid": true, + "kind": "compute", + "expect": 52957.07669974909, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [153.149965, 18.595315] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "I need the permeability for a Darcy number of 153.15 and a characteristic length of 18.5953, please.", + "a": "52957.07669974909", + "valid": true, + "kind": "compute", + "expect": 52957.07669974909, + "dtype": "quantity", + "unit": "m^2", + "why": "permeability for [153.149965, 18.595315] (the system Darcy number (Wikidata Q16954269))" + }, + { + "q": "If the Darcy number is 8.50728, what is the permeability?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the characteristic length is not given" + }, + { + "q": "Could you work out the permeability given Darcy number = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the characteristic length is not given" + }, + { + "q": "Do you know the permeability 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 permeability 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 permeability given Darcy number = -0.318734, characteristic length = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative Darcy number: no example had one" + }, + { + "q": "What is a typical permeability?", + "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-permeability/program.py b/root/organs10/physics/specialists/solved-permeability/program.py new file mode 100644 index 0000000000000000000000000000000000000000..59aba5323308366274d6e6cc8c369a36fb212e3c --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability/program.py @@ -0,0 +1,7 @@ +"""permeability from Darcy number, characteristic length (Darcy number (Wikidata Q16954269)) +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(darcy_number, characteristic_length): + return 1.0*characteristic_length**2*darcy_number diff --git a/root/organs10/physics/specialists/solved-permeability/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-permeability/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeability/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-permeance/organ_formula_v2.py b/root/organs10/physics/specialists/solved-permeance/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeance/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-permeance/panel.json b/root/organs10/physics/specialists/solved-permeance/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..d533e9984497e8601e7eacebec32587d7762b766 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeance/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the permeance for magnetic reluctance 107.961?", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [107.960666] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 107.961.", + "a": "0.00926263275385168", + "valid": true, + "kind": "compute", + "expect": 0.00926263275385168, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [107.960666] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance for magnetic reluctance 22.652?", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [22.652023] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 22.652.", + "a": "0.044146167826513254", + "valid": true, + "kind": "compute", + "expect": 0.044146167826513254, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [22.652023] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance for magnetic reluctance 173.394?", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [173.393638] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 173.394.", + "a": "0.0057672242718762815", + "valid": true, + "kind": "compute", + "expect": 0.0057672242718762815, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [173.393638] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance for magnetic reluctance 126.709?", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [126.709252] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 126.709.", + "a": "0.007892083536070259", + "valid": true, + "kind": "compute", + "expect": 0.007892083536070259, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [126.709252] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance for magnetic reluctance 0.671697?", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [0.671697] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 0.671697.", + "a": "1.4887660694527203", + "valid": true, + "kind": "compute", + "expect": 1.4887660694527203, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [0.671697] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance for magnetic reluctance 1.16997?", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [1.169968] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Tell me the permeance with magnetic reluctance of 1.16997.", + "a": "0.8547242274066585", + "valid": true, + "kind": "compute", + "expect": 0.8547242274066585, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [1.169968] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "What is the permeance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic reluctance is not given" + }, + { + "q": "Could you work out the permeance, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic reluctance is not given" + }, + { + "q": "What is the permeance 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 permeance 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 permeance with magnetic reluctance of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic reluctance: no example had one" + }, + { + "q": "Which permeance 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 reluctance is 2.57003, what is the permeance?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [2.57003] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Could you work out the permeance given magnetic reluctance = 2.57003?", + "a": "0.38910052946214563", + "valid": true, + "kind": "compute", + "expect": 0.38910052946214563, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [2.57003] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "I need the permeance for a magnetic reluctance of 48.921, please.", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [48.920991] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "If the magnetic reluctance is 48.921, what is the permeance?", + "a": "0.02044112317474344", + "valid": true, + "kind": "compute", + "expect": 0.02044112317474344, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [48.920991] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Could you work out the permeance given magnetic reluctance = 0.348438?", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [0.348438] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "I need the permeance for a magnetic reluctance of 0.348438, please.", + "a": "2.869953759769417", + "valid": true, + "kind": "compute", + "expect": 2.869953759769417, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [0.348438] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "If the magnetic reluctance is 252.709, what is the permeance?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [252.709024] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Could you work out the permeance given magnetic reluctance = 252.709?", + "a": "0.0039571202610184176", + "valid": true, + "kind": "compute", + "expect": 0.0039571202610184176, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [252.709024] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "I need the permeance for a magnetic reluctance of 20.3966, please.", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [20.396558] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "If the magnetic reluctance is 20.3966, what is the permeance?", + "a": "0.04902788018766951", + "valid": true, + "kind": "compute", + "expect": 0.04902788018766951, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [20.396558] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "Could you work out the permeance given magnetic reluctance = 134.993?", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [134.992958] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "I need the permeance for a magnetic reluctance of 134.993, please.", + "a": "0.007407793842889246", + "valid": true, + "kind": "compute", + "expect": 0.007407793842889246, + "dtype": "quantity", + "unit": "m^2*kg/s^2/A^2", + "why": "permeance for [134.992958] (the system permeance (Wikidata Q77997985))" + }, + { + "q": "I need the permeance, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic reluctance is not given" + }, + { + "q": "Can you tell me the permeance?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the magnetic reluctance is not given" + }, + { + "q": "Do you know the permeance 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 permeance 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 permeance given magnetic reluctance = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative magnetic reluctance: no example had one" + }, + { + "q": "What is a typical permeance?", + "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-permeance/program.py b/root/organs10/physics/specialists/solved-permeance/program.py new file mode 100644 index 0000000000000000000000000000000000000000..83b0c039cf6f107910638a93ede05a5d9adedbd9 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeance/program.py @@ -0,0 +1,7 @@ +"""permeance from magnetic reluctance (permeance (Wikidata Q77997985)) +The maths organ (systems.py): solved from the system q1 = ((1)/(q0)); checked by substitution into every equation and by a numeric solution at 12 points""" +import math + + +def compute(magnetic_reluctance): + return 1.0/magnetic_reluctance diff --git a/root/organs10/physics/specialists/solved-permeance/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-permeance/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permeance/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-permittivity/organ_formula_v2.py b/root/organs10/physics/specialists/solved-permittivity/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permittivity/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-permittivity/panel.json b/root/organs10/physics/specialists/solved-permittivity/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e798d239fb0fdbf8f4368c17df957705c5806959 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permittivity/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the permittivity for electric flux density 107.961 and electric field strength 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [107.960666, 59.4105] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 107.961 and electric field strength of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [107.960666, 59.4105] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 169.527 and electric field strength 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [169.526958, 280.773702] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 169.527 and electric field strength of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [169.526958, 280.773702] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 1.91195 and electric field strength 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [1.911952, 82.240072] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 1.91195 and electric field strength of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [1.911952, 82.240072] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 1.64379 and electric field strength 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [1.643795, 252.709024] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 1.64379 and electric field strength of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [1.643795, 252.709024] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 18.3169 and electric field strength 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [18.316867, 6.838598] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 18.3169 and electric field strength of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [18.316867, 6.838598] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 156.502 and electric field strength 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [156.50181, 185.886273] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Tell me the permittivity with electric flux density of 156.502 and electric field strength of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [156.50181, 185.886273] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "What is the permittivity for electric flux density 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Tell me the permittivity with electric flux density of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "What is the permittivity 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 permittivity 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 permittivity with electric flux density of -1.91195 and electric field strength of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative electric flux density: no example had one" + }, + { + "q": "Which permittivity 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 flux density is 8.50728 and the electric field strength is 17.7888, what is the permittivity?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [8.507283, 17.788778] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Could you work out the permittivity given electric flux density = 8.50728, electric field strength = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [8.507283, 17.788778] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "I need the permittivity for an electric flux density of 8.24951 and an electric field strength of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [8.24951, 0.634021] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "If the electric flux density is 8.24951 and the electric field strength is 0.634021, what is the permittivity?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [8.24951, 0.634021] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Could you work out the permittivity given electric flux density = 0.318734, electric field strength = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [0.318734, 9.566071] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "I need the permittivity for an electric flux density of 0.318734 and an electric field strength of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [0.318734, 9.566071] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "If the electric flux density is 0.671697 and the electric field strength is 14.2496, what is the permittivity?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [0.671697, 14.249569] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Could you work out the permittivity given electric flux density = 0.671697, electric field strength = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [0.671697, 14.249569] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "I need the permittivity for an electric flux density of 21.7931 and an electric field strength of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [21.793126, 29.510609] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "If the electric flux density is 21.7931 and the electric field strength is 29.5106, what is the permittivity?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [21.793126, 29.510609] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "Could you work out the permittivity given electric flux density = 153.15, electric field strength = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [153.149965, 18.595315] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "I need the permittivity for an electric flux density of 153.15 and an electric field strength of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "s^4*A^2/m^3/kg", + "why": "permittivity for [153.149965, 18.595315] (the system permittivity (Wikidata Q211569))" + }, + { + "q": "If the electric flux density is 8.50728, what is the permittivity?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Could you work out the permittivity given electric flux density = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the electric field strength is not given" + }, + { + "q": "Do you know the permittivity 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 permittivity 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 permittivity given electric flux density = -0.318734, electric field strength = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative electric flux density: no example had one" + }, + { + "q": "What is a typical permittivity?", + "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-permittivity/program.py b/root/organs10/physics/specialists/solved-permittivity/program.py new file mode 100644 index 0000000000000000000000000000000000000000..f358e143202c843bc3399571bd09c2f5caeaf991 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permittivity/program.py @@ -0,0 +1,7 @@ +"""permittivity from electric flux density, electric field strength (permittivity (Wikidata Q211569)) +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(electric_flux_density, electric_field_strength): + return 1.0*electric_flux_density/electric_field_strength diff --git a/root/organs10/physics/specialists/solved-permittivity/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-permittivity/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-permittivity/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-phase-angle-of-electric-curre/organ_formula_v2.py b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/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-phase-angle-of-electric-curre/panel.json b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..f6be6f9abd8637f97b61ab6bd5d75a85e1c0a9a2 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the phase angle of electric current for phase angle of voltage 107.961 and phase difference 59.4105?", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 107.961 and phase difference of 59.4105.", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 157.223 and phase difference 35.6412?", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [157.22256, 35.641157] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 157.223 and phase difference of 35.6412.", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [157.22256, 35.641157] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 126.709 and phase difference 1.70503?", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [126.709252, 1.705032] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 126.709 and phase difference of 1.70503.", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [126.709252, 1.705032] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 41.6566 and phase difference 13.8779?", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [41.656639, 13.877867] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 41.6566 and phase difference of 13.8779.", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [41.656639, 13.877867] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 8.50341 and phase difference 0.58813?", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [8.503407, 0.58813] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 8.50341 and phase difference of 0.58813.", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [8.503407, 0.58813] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 223.509 and phase difference 17.3414?", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [223.508796, 17.341435] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 223.509 and phase difference of 17.3414.", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [223.508796, 17.341435] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of electric current for phase angle of voltage 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Tell me the phase angle of electric current with phase angle of voltage of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "What is the phase angle of electric current 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 phase angle of electric current 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 phase angle of electric current with phase angle of voltage of -126.709 and phase difference of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of voltage: no example had one" + }, + { + "q": "Which phase angle of electric current 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 phase angle of voltage is 167.625 and the phase difference is 10.3291, what is the phase angle of electric current?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [167.624948, 10.329054] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of electric current given phase angle of voltage = 167.625, phase difference = 10.3291?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [167.624948, 10.329054] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of electric current for a phase angle of voltage of 13.999 and a phase difference of 0.348438, please.", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [13.999029, 0.348438] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 13.999 and the phase difference is 0.348438, what is the phase angle of electric current?", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [13.999029, 0.348438] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of electric current given phase angle of voltage = 81.1967, phase difference = 6.98086?", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [81.196705, 6.980857] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of electric current for a phase angle of voltage of 81.1967 and a phase difference of 6.98086, please.", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [81.196705, 6.980857] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 19.4474 and the phase difference is 4.51548, what is the phase angle of electric current?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [19.447357, 4.515475] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of electric current given phase angle of voltage = 19.4474, phase difference = 4.51548?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [19.447357, 4.515475] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of electric current for a phase angle of voltage of 13.2373 and a phase difference of 4.71941, please.", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [13.237311, 4.719415] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 13.2373 and the phase difference is 4.71941, what is the phase angle of electric current?", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [13.237311, 4.719415] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of electric current given phase angle of voltage = 21.7946, phase difference = 9.1061?", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [21.794621, 9.106104] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of electric current for a phase angle of voltage of 21.7946 and a phase difference of 9.1061, please.", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of electric current for [21.794621, 9.106104] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 167.625, what is the phase angle of electric current?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Could you work out the phase angle of electric current given phase angle of voltage = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Do you know the phase angle of electric current 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 phase angle of electric current 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 phase angle of electric current given phase angle of voltage = -81.1967, phase difference = 6.98086?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of voltage: no example had one" + }, + { + "q": "What is a typical phase angle of electric current?", + "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-phase-angle-of-electric-curre/program.py b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/program.py new file mode 100644 index 0000000000000000000000000000000000000000..5ebace067ceef82d89bf385709a447552b07e028 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/program.py @@ -0,0 +1,7 @@ +"""phase angle of electric current from phase angle of voltage, phase difference (voltage-current phase difference (Wikidata Q78514588)) +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(phase_angle_of_voltage, phase_difference): + return 1.0*phase_angle_of_voltage - 1.0*phase_difference diff --git a/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-electric-curre/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-phase-angle-of-voltage/organ_formula_v2.py b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/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-phase-angle-of-voltage/panel.json b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..77731493e96cfa261dd9a7bfa0b5e68892760443 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the phase angle of voltage for phase angle of electric current 107.961 and phase difference 59.4105?", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 107.961 and phase difference of 59.4105.", + "a": "167.37116608113337", + "valid": true, + "kind": "compute", + "expect": 167.37116608113337, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 169.527 and phase difference 280.774?", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [169.526958, 280.773702] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 169.527 and phase difference of 280.774.", + "a": "450.3006594796926", + "valid": true, + "kind": "compute", + "expect": 450.3006594796926, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [169.526958, 280.773702] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 1.91195 and phase difference 82.2401?", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [1.911952, 82.240072] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 1.91195 and phase difference of 82.2401.", + "a": "84.15202360564845", + "valid": true, + "kind": "compute", + "expect": 84.15202360564845, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [1.911952, 82.240072] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 1.64379 and phase difference 252.709?", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [1.643795, 252.709024] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 1.64379 and phase difference of 252.709.", + "a": "254.3528197443903", + "valid": true, + "kind": "compute", + "expect": 254.3528197443903, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [1.643795, 252.709024] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 18.3169 and phase difference 6.8386?", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [18.316867, 6.838598] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 18.3169 and phase difference of 6.8386.", + "a": "25.155465084200447", + "valid": true, + "kind": "compute", + "expect": 25.155465084200447, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [18.316867, 6.838598] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 156.502 and phase difference 185.886?", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [156.50181, 185.886273] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 156.502 and phase difference of 185.886.", + "a": "342.38808257181284", + "valid": true, + "kind": "compute", + "expect": 342.38808257181284, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [156.50181, 185.886273] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase angle of voltage for phase angle of electric current 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Tell me the phase angle of voltage with phase angle of electric current of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "What is the phase angle of voltage 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 phase angle of voltage 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 phase angle of voltage with phase angle of electric current of -1.91195 and phase difference of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of electric current: no example had one" + }, + { + "q": "Which phase angle of voltage 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 phase angle of electric current is 8.50728 and the phase difference is 17.7888, what is the phase angle of voltage?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [8.507283, 17.788778] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of voltage given phase angle of electric current = 8.50728, phase difference = 17.7888?", + "a": "26.296060781565316", + "valid": true, + "kind": "compute", + "expect": 26.296060781565316, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [8.507283, 17.788778] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of voltage for a phase angle of electric current of 8.24951 and a phase difference of 0.634021, please.", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [8.24951, 0.634021] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of electric current is 8.24951 and the phase difference is 0.634021, what is the phase angle of voltage?", + "a": "8.883530840552329", + "valid": true, + "kind": "compute", + "expect": 8.883530840552329, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [8.24951, 0.634021] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of voltage given phase angle of electric current = 0.318734, phase difference = 9.56607?", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [0.318734, 9.566071] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of voltage for a phase angle of electric current of 0.318734 and a phase difference of 9.56607, please.", + "a": "9.884805036334958", + "valid": true, + "kind": "compute", + "expect": 9.884805036334958, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [0.318734, 9.566071] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of electric current is 0.671697 and the phase difference is 14.2496, what is the phase angle of voltage?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [0.671697, 14.249569] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of voltage given phase angle of electric current = 0.671697, phase difference = 14.2496?", + "a": "14.921266515731517", + "valid": true, + "kind": "compute", + "expect": 14.921266515731517, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [0.671697, 14.249569] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of voltage for a phase angle of electric current of 21.7931 and a phase difference of 29.5106, please.", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [21.793126, 29.510609] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of electric current is 21.7931 and the phase difference is 29.5106, what is the phase angle of voltage?", + "a": "51.30373515218151", + "valid": true, + "kind": "compute", + "expect": 51.30373515218151, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [21.793126, 29.510609] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase angle of voltage given phase angle of electric current = 153.15, phase difference = 18.5953?", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [153.149965, 18.595315] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase angle of voltage for a phase angle of electric current of 153.15 and a phase difference of 18.5953, please.", + "a": "171.745280607835", + "valid": true, + "kind": "compute", + "expect": 171.745280607835, + "dtype": "quantity", + "unit": "1", + "why": "phase angle of voltage for [153.149965, 18.595315] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of electric current is 8.50728, what is the phase angle of voltage?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Could you work out the phase angle of voltage given phase angle of electric current = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase difference is not given" + }, + { + "q": "Do you know the phase angle of voltage 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 phase angle of voltage 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 phase angle of voltage given phase angle of electric current = -0.318734, phase difference = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of electric current: no example had one" + }, + { + "q": "What is a typical phase angle of voltage?", + "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-phase-angle-of-voltage/program.py b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/program.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e69970c76e5581de1007283d7952767f5a1346 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/program.py @@ -0,0 +1,7 @@ +"""phase angle of voltage from phase angle of electric current, phase difference (voltage-current phase difference (Wikidata Q78514588)) +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(phase_angle_of_electric_current, phase_difference): + return 1.0*phase_angle_of_electric_current + 1.0*phase_difference diff --git a/root/organs10/physics/specialists/solved-phase-angle-of-voltage/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-angle-of-voltage/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-phase-difference/organ_formula_v2.py b/root/organs10/physics/specialists/solved-phase-difference/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-difference/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-phase-difference/panel.json b/root/organs10/physics/specialists/solved-phase-difference/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..428bf72a6ea40ac91f53cf49a2192cc32694f91d --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-difference/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the phase difference for phase angle of voltage 107.961 and phase angle of electric current 59.4105?", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 107.961 and phase angle of electric current of 59.4105.", + "a": "48.55016569879068", + "valid": true, + "kind": "compute", + "expect": 48.55016569879068, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [107.960666, 59.4105] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 157.223 and phase angle of electric current 35.6412?", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [157.22256, 35.641157] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 157.223 and phase angle of electric current of 35.6412.", + "a": "121.5814030054458", + "valid": true, + "kind": "compute", + "expect": 121.5814030054458, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [157.22256, 35.641157] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 126.709 and phase angle of electric current 1.70503?", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [126.709252, 1.705032] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 126.709 and phase angle of electric current of 1.70503.", + "a": "125.00421942160824", + "valid": true, + "kind": "compute", + "expect": 125.00421942160824, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [126.709252, 1.705032] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 41.6566 and phase angle of electric current 13.8779?", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [41.656639, 13.877867] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 41.6566 and phase angle of electric current of 13.8779.", + "a": "27.77877186905885", + "valid": true, + "kind": "compute", + "expect": 27.77877186905885, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [41.656639, 13.877867] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 8.50341 and phase angle of electric current 0.58813?", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [8.503407, 0.58813] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 8.50341 and phase angle of electric current of 0.58813.", + "a": "7.91527752848457", + "valid": true, + "kind": "compute", + "expect": 7.91527752848457, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [8.503407, 0.58813] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 223.509 and phase angle of electric current 17.3414?", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [223.508796, 17.341435] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 223.509 and phase angle of electric current of 17.3414.", + "a": "206.1673613150397", + "valid": true, + "kind": "compute", + "expect": 206.1673613150397, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [223.508796, 17.341435] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "What is the phase difference for phase angle of voltage 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase angle of electric current is not given" + }, + { + "q": "Tell me the phase difference with phase angle of voltage of 157.223.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase angle of electric current is not given" + }, + { + "q": "What is the phase difference 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 phase difference 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 phase difference with phase angle of voltage of -126.709 and phase angle of electric current of 1.70503.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of voltage: no example had one" + }, + { + "q": "Which phase difference 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 phase angle of voltage is 167.625 and the phase angle of electric current is 10.3291, what is the phase difference?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [167.624948, 10.329054] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase difference given phase angle of voltage = 167.625, phase angle of electric current = 10.3291?", + "a": "157.29589332353083", + "valid": true, + "kind": "compute", + "expect": 157.29589332353083, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [167.624948, 10.329054] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase difference for a phase angle of voltage of 13.999 and a phase angle of electric current of 0.348438, please.", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [13.999029, 0.348438] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 13.999 and the phase angle of electric current is 0.348438, what is the phase difference?", + "a": "13.650591275493905", + "valid": true, + "kind": "compute", + "expect": 13.650591275493905, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [13.999029, 0.348438] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase difference given phase angle of voltage = 81.1967, phase angle of electric current = 6.98086?", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [81.196705, 6.980857] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase difference for a phase angle of voltage of 81.1967 and a phase angle of electric current of 6.98086, please.", + "a": "74.21584883614992", + "valid": true, + "kind": "compute", + "expect": 74.21584883614992, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [81.196705, 6.980857] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 19.4474 and the phase angle of electric current is 4.51548, what is the phase difference?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [19.447357, 4.515475] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase difference given phase angle of voltage = 19.4474, phase angle of electric current = 4.51548?", + "a": "14.931881955429075", + "valid": true, + "kind": "compute", + "expect": 14.931881955429075, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [19.447357, 4.515475] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase difference for a phase angle of voltage of 13.2373 and a phase angle of electric current of 4.71941, please.", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [13.237311, 4.719415] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 13.2373 and the phase angle of electric current is 4.71941, what is the phase difference?", + "a": "8.517896269006052", + "valid": true, + "kind": "compute", + "expect": 8.517896269006052, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [13.237311, 4.719415] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "Could you work out the phase difference given phase angle of voltage = 21.7946, phase angle of electric current = 9.1061?", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [21.794621, 9.106104] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "I need the phase difference for a phase angle of voltage of 21.7946 and a phase angle of electric current of 9.1061, please.", + "a": "12.68851669739933", + "valid": true, + "kind": "compute", + "expect": 12.68851669739933, + "dtype": "quantity", + "unit": "1", + "why": "phase difference for [21.794621, 9.106104] (the system voltage-current phase difference (Wikidata Q78514588))" + }, + { + "q": "If the phase angle of voltage is 167.625, what is the phase difference?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase angle of electric current is not given" + }, + { + "q": "Could you work out the phase difference given phase angle of voltage = 13.999?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the phase angle of electric current is not given" + }, + { + "q": "Do you know the phase difference 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 phase difference 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 phase difference given phase angle of voltage = -81.1967, phase angle of electric current = 6.98086?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative phase angle of voltage: no example had one" + }, + { + "q": "What is a typical phase difference?", + "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-phase-difference/program.py b/root/organs10/physics/specialists/solved-phase-difference/program.py new file mode 100644 index 0000000000000000000000000000000000000000..0a6e9c92f4598130d552c5ebdc802217d3a92a1d --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-difference/program.py @@ -0,0 +1,7 @@ +"""phase difference from phase angle of voltage, phase angle of electric current (voltage-current phase difference (Wikidata Q78514588)) +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(phase_angle_of_voltage, phase_angle_of_electric_current): + return -1.0*phase_angle_of_electric_current + 1.0*phase_angle_of_voltage diff --git a/root/organs10/physics/specialists/solved-phase-difference/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-phase-difference/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-difference/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-phase-speed-of-electromagneti/organ_formula_v2.py b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/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-phase-speed-of-electromagneti/panel.json b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..1fc38af448cdd7a6f56c8afe0ce3b84d3c0cd088 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 107.961 and angular wavenumber 59.4105?", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [107.960666, 59.4105] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 107.961 and angular wavenumber of 59.4105.", + "a": "1.8171983999893246", + "valid": true, + "kind": "compute", + "expect": 1.8171983999893246, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [107.960666, 59.4105] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 169.527 and angular wavenumber 280.774?", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [169.526958, 280.773702] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 169.527 and angular wavenumber of 280.774.", + "a": "0.6037850281809957", + "valid": true, + "kind": "compute", + "expect": 0.6037850281809957, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [169.526958, 280.773702] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 1.91195 and angular wavenumber 82.2401?", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [1.911952, 82.240072] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 1.91195 and angular wavenumber of 82.2401.", + "a": "0.023248420388592404", + "valid": true, + "kind": "compute", + "expect": 0.023248420388592404, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [1.911952, 82.240072] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 1.64379 and angular wavenumber 252.709?", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [1.643795, 252.709024] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 1.64379 and angular wavenumber of 252.709.", + "a": "0.006504696457692342", + "valid": true, + "kind": "compute", + "expect": 0.006504696457692342, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [1.643795, 252.709024] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 18.3169 and angular wavenumber 6.8386?", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [18.316867, 6.838598] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 18.3169 and angular wavenumber of 6.8386.", + "a": "2.6784535160942915", + "valid": true, + "kind": "compute", + "expect": 2.6784535160942915, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [18.316867, 6.838598] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 156.502 and angular wavenumber 185.886?", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [156.50181, 185.886273] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 156.502 and angular wavenumber of 185.886.", + "a": "0.8419223616111585", + "valid": true, + "kind": "compute", + "expect": 0.8419223616111585, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [156.50181, 185.886273] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "What is the phase speed of electromagnetic waves for angular frequency 107.961?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular wavenumber is not given" + }, + { + "q": "Tell me the phase speed of electromagnetic waves with angular frequency of 169.527.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular wavenumber is not given" + }, + { + "q": "What is the phase speed of electromagnetic waves 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 phase speed of electromagnetic waves 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 phase speed of electromagnetic waves with angular frequency of -1.91195 and angular wavenumber of 82.2401.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular frequency: no example had one" + }, + { + "q": "Which phase speed of electromagnetic waves 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 frequency is 8.50728 and the angular wavenumber is 17.7888, what is the phase speed of electromagnetic waves?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [8.507283, 17.788778] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Could you work out the phase speed of electromagnetic waves given angular frequency = 8.50728, angular wavenumber = 17.7888?", + "a": "0.4782387296673114", + "valid": true, + "kind": "compute", + "expect": 0.4782387296673114, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [8.507283, 17.788778] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "I need the phase speed of electromagnetic waves for an angular frequency of 8.24951 and an angular wavenumber of 0.634021, please.", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [8.24951, 0.634021] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "If the angular frequency is 8.24951 and the angular wavenumber is 0.634021, what is the phase speed of electromagnetic waves?", + "a": "13.011414796588832", + "valid": true, + "kind": "compute", + "expect": 13.011414796588832, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [8.24951, 0.634021] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Could you work out the phase speed of electromagnetic waves given angular frequency = 0.318734, angular wavenumber = 9.56607?", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [0.318734, 9.566071] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "I need the phase speed of electromagnetic waves for an angular frequency of 0.318734 and an angular wavenumber of 9.56607, please.", + "a": "0.03331922249257168", + "valid": true, + "kind": "compute", + "expect": 0.03331922249257168, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [0.318734, 9.566071] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "If the angular frequency is 0.671697 and the angular wavenumber is 14.2496, what is the phase speed of electromagnetic waves?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [0.671697, 14.249569] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Could you work out the phase speed of electromagnetic waves given angular frequency = 0.671697, angular wavenumber = 14.2496?", + "a": "0.04713807027437235", + "valid": true, + "kind": "compute", + "expect": 0.04713807027437235, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [0.671697, 14.249569] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "I need the phase speed of electromagnetic waves for an angular frequency of 21.7931 and an angular wavenumber of 29.5106, please.", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [21.793126, 29.510609] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "If the angular frequency is 21.7931 and the angular wavenumber is 29.5106, what is the phase speed of electromagnetic waves?", + "a": "0.7384844800541926", + "valid": true, + "kind": "compute", + "expect": 0.7384844800541926, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [21.793126, 29.510609] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "Could you work out the phase speed of electromagnetic waves given angular frequency = 153.15, angular wavenumber = 18.5953?", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [153.149965, 18.595315] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "I need the phase speed of electromagnetic waves for an angular frequency of 153.15 and an angular wavenumber of 18.5953, please.", + "a": "8.235943368499306", + "valid": true, + "kind": "compute", + "expect": 8.235943368499306, + "dtype": "quantity", + "unit": "m/s", + "why": "phase speed of electromagnetic waves for [153.149965, 18.595315] (the system phase speed of electromagnetic waves (Wikidata Q77990619))" + }, + { + "q": "If the angular frequency is 8.50728, what is the phase speed of electromagnetic waves?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular wavenumber is not given" + }, + { + "q": "Could you work out the phase speed of electromagnetic waves given angular frequency = 8.24951?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the angular wavenumber is not given" + }, + { + "q": "Do you know the phase speed of electromagnetic waves 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 phase speed of electromagnetic waves 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 phase speed of electromagnetic waves given angular frequency = -0.318734, angular wavenumber = 9.56607?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative angular frequency: no example had one" + }, + { + "q": "What is a typical phase speed of electromagnetic waves?", + "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-phase-speed-of-electromagneti/program.py b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/program.py new file mode 100644 index 0000000000000000000000000000000000000000..35629f32f965f0c1004ebabef18ca6ed88b51e8b --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/program.py @@ -0,0 +1,7 @@ +"""phase speed of electromagnetic waves from angular frequency, angular wavenumber (phase speed of electromagnetic waves (Wikidata Q77990619)) +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_frequency, angular_wavenumber): + return 1.0*angular_frequency/angular_wavenumber diff --git a/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-phase-speed-of-electromagneti/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-photon-energy/organ_formula_v2.py b/root/organs10/physics/specialists/solved-photon-energy/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-photon-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-photon-energy/panel.json b/root/organs10/physics/specialists/solved-photon-energy/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..e78d89533516a6ac371b14c99324facad927236c --- /dev/null +++ b/root/organs10/physics/specialists/solved-photon-energy/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the photon energy for light frequency 107.961?", + "a": "7.153549337519273e-32", + "valid": true, + "kind": "compute", + "expect": 7.153549337519273e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [107.960666] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 107.961.", + "a": "7.153549337519273e-32", + "valid": true, + "kind": "compute", + "expect": 7.153549337519273e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [107.960666] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy for light frequency 22.652?", + "a": "1.5009388959964317e-32", + "valid": true, + "kind": "compute", + "expect": 1.5009388959964317e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [22.652023] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 22.652.", + "a": "1.5009388959964317e-32", + "valid": true, + "kind": "compute", + "expect": 1.5009388959964317e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [22.652023] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy for light frequency 173.394?", + "a": "1.1489183925639683e-31", + "valid": true, + "kind": "compute", + "expect": 1.1489183925639683e-31, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [173.393638] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 173.394.", + "a": "1.1489183925639683e-31", + "valid": true, + "kind": "compute", + "expect": 1.1489183925639683e-31, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [173.393638] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy for light frequency 126.709?", + "a": "8.395843771440044e-32", + "valid": true, + "kind": "compute", + "expect": 8.395843771440044e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [126.709252] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 126.709.", + "a": "8.395843771440044e-32", + "valid": true, + "kind": "compute", + "expect": 8.395843771440044e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [126.709252] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy for light frequency 0.671697?", + "a": "4.4507126915082e-34", + "valid": true, + "kind": "compute", + "expect": 4.4507126915082e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [0.671697] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 0.671697.", + "a": "4.4507126915082e-34", + "valid": true, + "kind": "compute", + "expect": 4.4507126915082e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [0.671697] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy for light frequency 1.16997?", + "a": "7.752289952168941e-34", + "valid": true, + "kind": "compute", + "expect": 7.752289952168941e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [1.169968] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Tell me the photon energy with light frequency of 1.16997.", + "a": "7.752289952168941e-34", + "valid": true, + "kind": "compute", + "expect": 7.752289952168941e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [1.169968] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "What is the photon energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Could you work out the photon energy, please?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "What is the photon 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 photon 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 photon energy with light frequency of -173.394.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative light frequency: no example had one" + }, + { + "q": "Which photon 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 light frequency is 2.57003, what is the photon energy?", + "a": "1.7029198210445072e-33", + "valid": true, + "kind": "compute", + "expect": 1.7029198210445072e-33, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [2.57003] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Could you work out the photon energy given light frequency = 2.57003?", + "a": "1.7029198210445072e-33", + "valid": true, + "kind": "compute", + "expect": 1.7029198210445072e-33, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [2.57003] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "I need the photon energy for a light frequency of 48.921, please.", + "a": "3.2415391186463825e-32", + "valid": true, + "kind": "compute", + "expect": 3.2415391186463825e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [48.920991] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "If the light frequency is 48.921, what is the photon energy?", + "a": "3.2415391186463825e-32", + "valid": true, + "kind": "compute", + "expect": 3.2415391186463825e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [48.920991] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Could you work out the photon energy given light frequency = 0.348438?", + "a": "2.308772403542963e-34", + "valid": true, + "kind": "compute", + "expect": 2.308772403542963e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [0.348438] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "I need the photon energy for a light frequency of 0.348438, please.", + "a": "2.308772403542963e-34", + "valid": true, + "kind": "compute", + "expect": 2.308772403542963e-34, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [0.348438] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "If the light frequency is 252.709, what is the photon energy?", + "a": "1.6744676944174278e-31", + "valid": true, + "kind": "compute", + "expect": 1.6744676944174278e-31, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [252.709024] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Could you work out the photon energy given light frequency = 252.709?", + "a": "1.6744676944174278e-31", + "valid": true, + "kind": "compute", + "expect": 1.6744676944174278e-31, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [252.709024] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "I need the photon energy for a light frequency of 20.3966, please.", + "a": "1.351490216308894e-32", + "valid": true, + "kind": "compute", + "expect": 1.351490216308894e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [20.396558] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "If the light frequency is 20.3966, what is the photon energy?", + "a": "1.351490216308894e-32", + "valid": true, + "kind": "compute", + "expect": 1.351490216308894e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [20.396558] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "Could you work out the photon energy given light frequency = 134.993?", + "a": "8.944727918367188e-32", + "valid": true, + "kind": "compute", + "expect": 8.944727918367188e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [134.992958] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "I need the photon energy for a light frequency of 134.993, please.", + "a": "8.944727918367188e-32", + "valid": true, + "kind": "compute", + "expect": 8.944727918367188e-32, + "dtype": "quantity", + "unit": "J", + "why": "photon energy for [134.992958] (the system photon energy (Wikidata Q25303639))" + }, + { + "q": "I need the photon energy, please.", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Can you tell me the photon energy?", + "a": "", + "valid": false, + "kind": "missing_input", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "the light frequency is not given" + }, + { + "q": "Do you know the photon 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 photon 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 photon energy given light frequency = -0.348438?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative light frequency: no example had one" + }, + { + "q": "What is a typical photon 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-photon-energy/program.py b/root/organs10/physics/specialists/solved-photon-energy/program.py new file mode 100644 index 0000000000000000000000000000000000000000..429505359528dc047783d188167d7a307c04eca6 --- /dev/null +++ b/root/organs10/physics/specialists/solved-photon-energy/program.py @@ -0,0 +1,7 @@ +"""photon energy from light frequency (photon energy (Wikidata Q25303639)) +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(light_frequency): + return 6.62607004e-34*light_frequency diff --git a/root/organs10/physics/specialists/solved-photon-energy/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-photon-energy/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-photon-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-pipe-radius/organ_formula_v2.py b/root/organs10/physics/specialists/solved-pipe-radius/organ_formula_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..af7f3adaf0b052c69462e0e7d04e75a36c3dc020 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-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-pipe-radius/panel.json b/root/organs10/physics/specialists/solved-pipe-radius/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..1862f8b2508c8acaaa40be8c8603d169912241e4 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius/panel.json @@ -0,0 +1,366 @@ +{ + "dev": [ + { + "q": "What is the pipe radius for relaxation time 107.961, elasticity number 59.4105 and kinematic viscosity 5.77717?", + "a": "3.2401009696770915", + "valid": true, + "kind": "compute", + "expect": 3.2401009696770915, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [107.960666, 59.4105, 5.777165] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 107.961, elasticity number of 59.4105 and kinematic viscosity of 5.77717.", + "a": "3.2401009696770915", + "valid": true, + "kind": "compute", + "expect": 3.2401009696770915, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [107.960666, 59.4105, 5.777165] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 85.2416, elasticity number 160.878 and kinematic viscosity 2.69428?", + "a": "1.1948084415446603", + "valid": true, + "kind": "compute", + "expect": 1.1948084415446603, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [85.241623, 160.878442, 2.69428] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 85.2416, elasticity number of 160.878 and kinematic viscosity of 2.69428.", + "a": "1.1948084415446603", + "valid": true, + "kind": "compute", + "expect": 1.1948084415446603, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [85.241623, 160.878442, 2.69428] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 45.6157, elasticity number 4.97131 and kinematic viscosity 94.305?", + "a": "29.416376944564785", + "valid": true, + "kind": "compute", + "expect": 29.416376944564785, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [45.61567, 4.971307, 94.305046] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 45.6157, elasticity number of 4.97131 and kinematic viscosity of 94.305.", + "a": "29.416376944564785", + "valid": true, + "kind": "compute", + "expect": 29.416376944564785, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [45.61567, 4.971307, 94.305046] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 10.5638, elasticity number 198.839 and kinematic viscosity 0.671697?", + "a": "0.18890654119717645", + "valid": true, + "kind": "compute", + "expect": 0.18890654119717645, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [10.563843, 198.838955, 0.671697] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 10.5638, elasticity number of 198.839 and kinematic viscosity of 0.671697.", + "a": "0.18890654119717645", + "valid": true, + "kind": "compute", + "expect": 0.18890654119717645, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [10.563843, 198.838955, 0.671697] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 21.7931, elasticity number 29.5106 and kinematic viscosity 8.50341?", + "a": "2.5059198386980013", + "valid": true, + "kind": "compute", + "expect": 2.5059198386980013, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.793126, 29.510609, 8.503407] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 21.7931, elasticity number of 29.5106 and kinematic viscosity of 8.50341.", + "a": "2.5059198386980013", + "valid": true, + "kind": "compute", + "expect": 2.5059198386980013, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.793126, 29.510609, 8.503407] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 223.509, elasticity number 17.3414 and kinematic viscosity 7.10705?", + "a": "9.570826726293298", + "valid": true, + "kind": "compute", + "expect": 9.570826726293298, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [223.508796, 17.341435, 7.107049] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Tell me the pipe radius with relaxation time of 223.509, elasticity number of 17.3414 and kinematic viscosity of 7.10705.", + "a": "9.570826726293298", + "valid": true, + "kind": "compute", + "expect": 9.570826726293298, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [223.508796, 17.341435, 7.107049] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "What is the pipe radius for relaxation time 107.961 and elasticity number 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 relaxation time of 85.2416 and elasticity number 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 relaxation time of -45.6157, elasticity number of 4.97131 and kinematic viscosity of 94.305.", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relaxation time: 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 relaxation time is 17.7888, elasticity number is 167.625 and the kinematic viscosity is 10.3291, what is the pipe radius?", + "a": "1.046969463811213", + "valid": true, + "kind": "compute", + "expect": 1.046969463811213, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [17.788778, 167.624948, 10.329054] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the pipe radius given relaxation time = 17.7888, elasticity number = 167.625, kinematic viscosity = 10.3291?", + "a": "1.046969463811213", + "valid": true, + "kind": "compute", + "expect": 1.046969463811213, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [17.788778, 167.624948, 10.329054] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the pipe radius for a relaxation time of 21.511, an elasticity number of 173.394 and a kinematic viscosity of 251.084, please.", + "a": "5.581146621636312", + "valid": true, + "kind": "compute", + "expect": 5.581146621636312, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.511016, 173.393638, 251.084037] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the relaxation time is 21.511, elasticity number is 173.394 and the kinematic viscosity is 251.084, what is the pipe radius?", + "a": "5.581146621636312", + "valid": true, + "kind": "compute", + "expect": 5.581146621636312, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [21.511016, 173.393638, 251.084037] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the pipe radius given relaxation time = 129.245, elasticity number = 1.18359, kinematic viscosity = 15.9416?", + "a": "41.72269199630706", + "valid": true, + "kind": "compute", + "expect": 41.72269199630706, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [129.244984, 1.18359, 15.941612] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the pipe radius for a relaxation time of 129.245, an elasticity number of 1.18359 and a kinematic viscosity of 15.9416, please.", + "a": "41.72269199630706", + "valid": true, + "kind": "compute", + "expect": 41.72269199630706, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [129.244984, 1.18359, 15.941612] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the relaxation time is 20.3966, elasticity number is 18.3169 and the kinematic viscosity is 6.8386, what is the pipe radius?", + "a": "2.759538039597842", + "valid": true, + "kind": "compute", + "expect": 2.759538039597842, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [20.396558, 18.316867, 6.838598] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the pipe radius given relaxation time = 20.3966, elasticity number = 18.3169, kinematic viscosity = 6.8386?", + "a": "2.759538039597842", + "valid": true, + "kind": "compute", + "expect": 2.759538039597842, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [20.396558, 18.316867, 6.838598] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the pipe radius for a relaxation time of 185.886, an elasticity number of 13.2373 and a kinematic viscosity of 4.71941, please.", + "a": "8.140814290434816", + "valid": true, + "kind": "compute", + "expect": 8.140814290434816, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [185.886273, 13.237311, 4.719415] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the relaxation time is 185.886, elasticity number is 13.2373 and the kinematic viscosity is 4.71941, what is the pipe radius?", + "a": "8.140814290434816", + "valid": true, + "kind": "compute", + "expect": 8.140814290434816, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [185.886273, 13.237311, 4.719415] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "Could you work out the pipe radius given relaxation time = 9.1061, elasticity number = 24.5721, kinematic viscosity = 108.451?", + "a": "6.339597067504287", + "valid": true, + "kind": "compute", + "expect": 6.339597067504287, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [9.106104, 24.572086, 108.450792] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "I need the pipe radius for a relaxation time of 9.1061, an elasticity number of 24.5721 and a kinematic viscosity of 108.451, please.", + "a": "6.339597067504287", + "valid": true, + "kind": "compute", + "expect": 6.339597067504287, + "dtype": "quantity", + "unit": "m", + "why": "pipe radius for [9.106104, 24.572086, 108.450792] (the system elasticity number (Wikidata Q102310770))" + }, + { + "q": "If the relaxation time is 17.7888 and the elasticity number 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 relaxation time = 21.511, elasticity number = 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 relaxation time = -129.245, elasticity number = 1.18359, kinematic viscosity = 15.9416?", + "a": "", + "valid": false, + "kind": "out_of_domain", + "expect": null, + "dtype": "quantity", + "unit": "", + "why": "a negative relaxation time: 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/program.py b/root/organs10/physics/specialists/solved-pipe-radius/program.py new file mode 100644 index 0000000000000000000000000000000000000000..d6660589291e8e969be1c3d62b67ac46a501a9ff --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-radius/program.py @@ -0,0 +1,7 @@ +"""pipe radius from relaxation time, elasticity number, kinematic viscosity (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(relaxation_time, elasticity_number, kinematic_viscosity): + return 1.0*elasticity_number**(-0.5)*kinematic_viscosity**0.5*relaxation_time**0.5 diff --git a/root/organs10/physics/specialists/solved-pipe-radius/scorer_formula_v1.py b/root/organs10/physics/specialists/solved-pipe-radius/scorer_formula_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4680b0c332b5a679436933c30780b243a4c9f1 --- /dev/null +++ b/root/organs10/physics/specialists/solved-pipe-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"(?