File size: 8,979 Bytes
2419253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
"""The Oracle7 kernel, v2 (KERNEL_SPEC.md step K2): ONE kernel over declared and induced faces.

  READER   glue v3's reader gives every given's SI value, dimension and surface span. The kernel adds each given's
           QUANTITY NOUN from the words just before it, matched only against nouns the admitted formula parts use (the
           longest known noun ending there: "a density of 7850 kg per cubic metre" -> density), and the WANTED noun as the
           longest known noun in the question's asking clause ("what is its mass" -> mass).
  DECLARED the formula parts (830), planned by kernel v1: keys = noun + dimension, system-aware links, every plan agrees.
           Used only when every given and the wanted quantity are named.
  INDUCED  the specialists, through glue v3's learned faces, typed medium and law (conditions, coverage, named ratios).
  LAW      both readings answer -> they must agree (relative 1%), else the kernel declines ("two readings disagree").
           One answers -> that answer, with its receipts. Neither -> a hole: what was wanted, what was given, why.
usage: kernel_v2.py  (module; see run_kernel_dev.py)"""
from __future__ import annotations

import collections
import json
import os
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE))
from kernel_v1 import Kernel1  # noqa: E402
from kernel_v0 import ORGAN  # noqa: E402

ORGAN_DIR = ORGAN / "specialists"
from network_glue_v3 import GlueNetwork3, reader  # noqa: E402

STOP_TAIL = {"of", "is", "was", "at", "a", "an", "the", "its", "with", "has", "=", "to", "by", "about", "and", "in", "for"}


def to7(d6):
    """glue (m, kg, s, A, K, $) -> formula side (m, kg, s, A, K, mol, cd); money has no formula-side dimension"""
    if d6[5]:
        return None
    return (d6[0], d6[1], d6[2], d6[3], d6[4], 0, 0)


WORD = re.compile(r"[a-z][a-z\-]+")
TITLE_STOP = {"from", "the", "a", "an", "of", "and", "in", "on", "by", "for", "to", "with", "wikidata", "per", "unit", "system"}


class Declared(Kernel1):
    """kernel v1's declared side, with SYSTEM CONDITIONS replacing v1's link rule. A key several systems produce (a cone's
    height and a cylinder's height are both 'height') is produced, for a given question, only by systems the question
    names: a system's distinguishing words are its titles' words that no other system producing that key uses. A key one
    system produces needs no naming. (v1's rule blocked valid chains such as sphere volume -> mass through density.)"""

    def __init__(self, *a, **k):
        super().__init__(*a, **k)
        self.sys_words = collections.defaultdict(set)
        for pid, p in self.parts.items():
            try:
                t = json.loads((ORGAN_DIR / pid / "spec.json").read_text(encoding="utf-8")).get("title", "")
            except Exception:  # noqa: BLE001
                t = ""
            self.sys_words[self.sys[pid]] |= {w for w in WORD.findall(t.lower()) if w not in TITLE_STOP}
        # rivals: systems giving the SAME output from the SAME inputs (alternative models, e.g. cone vs cylinder volume
        # from radius and height). Systems that reach an output from different inputs are told apart by the givens.
        self.key_systems = collections.defaultdict(set)
        for p in self.parts.values():
            self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))].add(self.sys[p["id"]])
        self.qwords = set()

    def allowed(self, p):
        systems = self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))]
        if len(systems) <= 1:
            return True
        mine = self.sys_words[self.sys[p["id"]]]
        others = set().union(*(self.sys_words[s] for s in systems if s != self.sys[p["id"]]))
        return bool((mine - others) & self.qwords)

    def linked_ok(self, plan, given):
        return all(self.allowed(p) for p in plan)


class Kernel2:
    def __init__(self, standing, spec_root="/opt/o7spec", combo="/opt/o7spec/_fam"):
        self.declared = Declared()
        self.induced = GlueNetwork3(standing, spec_root, combo, log=lambda s: None)
        self.nouns = sorted({k[0] for k in self.declared.keys}, key=lambda n: -len(n))
        self.noun_dims = {}
        for (n, d) in self.declared.keys:
            self.noun_dims.setdefault(n, set()).add(d)

    def _noun_before(self, text, span):
        i = text.find(span)
        if i < 0:
            return None
        words = re.findall(r"[a-z][a-z\-]*", text[:i].lower())
        while words and words[-1] in STOP_TAIL:
            words.pop()
        for n in self.nouns:                      # longest first
            nw = n.split()
            if len(nw) <= len(words) and words[-len(nw):] == nw:
                return n
        return None

    def _wanted(self, text):
        sents = [s for s in re.split(r"(?<=[.?!])\s+", text.strip()) if s]
        ask = (sents[-1] if sents else text).lower()
        best = None
        for n in self.nouns:
            if re.search(r"\b%s\b" % re.escape(n), ask):
                best = n
                break
        return best

    def _leaves(self, want, d7, depth=3):
        """every input key that appears in some chain (depth <= 3) toward the wanted key, among parts this question allows"""
        seen, frontier, leaves = set(), [(want, d7)], set()
        for _ in range(depth):
            nxt = []
            for key in frontier:
                for p in self.declared.planner.by_out.get(key, []):
                    if p["id"] in seen or not self.declared.allowed(p):
                        continue
                    seen.add(p["id"])
                    for ik in p["in_keys"]:
                        leaves.add(ik)
                        nxt.append(ik)
            frontier = nxt
        return leaves

    def declared_answer(self, text):
        t = reader.normalise(text)
        givens, flags = reader.read_givens(t)
        goal = reader.read_goal(t)
        if not givens or flags.get("unread_numbers") or goal is None or goal[0] != "dim":
            return None, "declared: question not fully read"
        want = self._wanted(t)
        gd7 = to7(goal[1])
        if want is None or gd7 is None or gd7 not in self.noun_dims.get(want, set()):
            return None, "declared: no wanted quantity a part produces"
        self.declared.qwords = {w for w in WORD.findall(t.lower())}
        leaves = self._leaves(want, gd7)
        given, unnamed = {}, []
        for q in givens:
            n = self._noun_before(t, q.text)
            d7 = to7(q.dim)
            if d7 is None:
                return None, "declared: money has no formula-side quantity"
            if n is None or d7 not in self.noun_dims.get(n, set()):
                unnamed.append((q, d7))           # named by its dimension below, if that is unambiguous
                continue
            if (n, d7) in given:
                return None, "declared: two givens of the same quantity"
            given[(n, d7)] = q.v
        for q, d7 in unnamed:
            cands = [key for key in leaves if key[1] == d7 and key not in given]
            if len(cands) != 1:
                return None, "declared: %s names no quantity, and its dimension fits %d inputs" % (q.text, len(cands))
            given[cands[0]] = q.v
        r = self.declared.ask_keys(want, given)
        if r["status"] != "answered":
            return None, "declared: " + r.get("why", "")
        val = r["value"] / goal[3]
        unit = goal[2]
        return {"status": "answered", "answer": ("$%.2f" % val) if unit == "$" else "%s %s" % (reader.g(round(val, 6)), unit),
                "value_si": r["value"], "path": [x["part"] for x in r["receipts"]], "receipts": r["receipts"],
                "reading": "declared"}, None

    def solve(self, text):
        a, why_a = self.declared_answer(text)
        b = self.induced.solve(text)
        b_ok = b.get("status") == "answered"
        if a and b_ok:
            vb = _num(b.get("answer"))
            va = _num(a["answer"])
            if va is not None and vb is not None and abs(va - vb) > 0.01 * max(abs(va), abs(vb), 1e-12):
                return {"status": "declined", "reason": "two readings disagree: declared %s, induced %s" % (a["answer"], b["answer"]),
                        "check": "readings agree"}
            return dict(a, also_induced=b.get("answer"), trace=b.get("trace", []))
        if a:
            return dict(a, trace=[{"node": p} for p in a["path"]])
        if b_ok:
            return dict(b, reading="induced")
        return {"status": "declined", "reason": b.get("reason") or why_a, "declared_reason": why_a,
                "hole": {"question": text, "declared": why_a, "induced": b.get("reason")}}


def _num(ans):
    m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?", str(ans or "").replace("$", ""))
    return float(m.group(0).replace(",", "")) if m else None