File size: 8,970 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""The Oracle7 kernel, v4: the goal reader. Found by the OpenStax held-out run (126 of 136 independent textbook exercises
declined because the question's GOAL was unread: the reader only knew goals with a unit spelled out, "in kWh").
A goal is now also read from:
  1. the wanted quantity NOUN the kernel's parts declare ("What is its acceleration?" -> acceleration, its dimension from
     the parts; answered in SI), when that noun has exactly one dimension among the parts;
  2. the closed class of English wh-idioms that ask for a quantity: how far / how high / how tall / how deep / how long
     (a distance) -> length; how long (with a time verb) / how much time -> time; how fast / how quickly -> speed;
     how heavy -> mass; how much energy / heat / work -> energy. (A closed list, like the unit table: English grammar,
     not data about any question.)
The answer is given in the SI unit of that dimension. Everything else is kernel v3 (validity on every path).
usage: module"""
from __future__ import annotations

import re

from kernel_v3 import Kernel3, reader

L, M, T = (1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0)
V, E = (1, 0, -1, 0, 0, 0), (2, 1, -2, 0, 0, 0)
SI_NAME = {L: "m", M: "kg", T: "s", V: "m/s", E: "J", (1, 0, -2, 0, 0, 0): "m/s^2", (1, 1, -2, 0, 0, 0): "N",
           (2, 1, -3, 0, 0, 0): "W", (-1, 1, -2, 0, 0, 0): "Pa", (3, 0, 0, 0, 0, 0): "m^3", (2, 0, 0, 0, 0, 0): "m^2",
           (0, 0, -1, 0, 0, 0): "Hz", (-3, 1, 0, 0, 0, 0): "kg/m^3", (1, 1, -1, 0, 0, 0): "kg m/s",
           (0, 0, 0, 0, 1, 0): "K", (0, 0, 0, 1, 0, 0): "A"}
TIME_VERB = re.compile(r"\bhow long\b[^?]*\b(take|last|wait|stay|remain|run|burn|fall|travel|until|before)\b", re.I)
IDIOMS = [(re.compile(r"\bhow (far|high|tall|deep)\b", re.I), L), (re.compile(r"\bhow (fast|quickly)\b", re.I), V),
          (re.compile(r"\bhow heavy\b", re.I), M), (re.compile(r"\bhow much (time)\b", re.I), T),
          (re.compile(r"\bhow much (energy|heat|work)\b", re.I), E)]


def _from7(d7):
    return (d7[0], d7[1], d7[2], d7[3], d7[4], 0) if not (d7[5] or d7[6]) else None


class Kernel4(Kernel3):
    def __init__(self, *a, **k):
        super().__init__(*a, **k)
        self._glue_solve = self.induced.solve          # glue v3 as frozen, kept for comparison
        self.induced.solve = self._induced_solve       # the kernel's induced path: slot cues + no self-cancellation

    def goal_of(self, text):
        t = reader.normalise(text)
        g = reader.read_goal(t)
        if g is not None:
            return g
        g = self._implicit_goal(t)
        if g is None:
            return None
        # an implicit goal answers in the unit the question itself uses for that dimension, else SI
        givens, _ = reader.read_givens(t)
        for q in givens:
            if q.dim == g[1]:
                m = re.match(r"\s*-?[\d.,]+\s*(.+?)\s*$", q.text)
                u = reader.unit_lookup(m.group(1)) if m else None
                if u and u[1] == g[1]:
                    return ("dim", g[1], m.group(1), u[0])
        return g

    def _implicit_goal(self, t):
        ask = self._asking(t)
        if TIME_VERB.search(ask):
            return ("dim", T, "s", 1)
        for rx, d in IDIOMS:
            if rx.search(ask):
                return ("dim", d, SI_NAME[d], 1)
        want = self._wanted(t)
        if want:
            dims = {_from7(d) for d in self.noun_dims.get(want, set())} - {None}
            if len(dims) == 1:
                d = dims.pop()
                if d in SI_NAME:
                    return ("dim", d, SI_NAME[d], 1)
        return None

    @staticmethod
    def _asking(t):
        """the sentence that asks: the last one ending in '?', else the last one with a wh-word or an imperative ask"""
        sents = [s for s in re.split(r"(?<=[.?!])\s+", t.strip()) if s] or [t]
        asks = [s for s in sents if s.endswith("?")]
        if asks:
            return asks[-1]
        asks = [s for s in sents if re.search(r"\b(what|how|which|calculate|find|determine|compute)\b", s, re.I)]
        return asks[-1] if asks else sents[-1]

    def _wanted(self, text):
        # v2 read the wanted noun from the LAST sentence; a stated fact after the question ("The nail puller has a mass
        # of 2.10 kg.", "Assume coffee has the same density as water.") then became the goal. The asking sentence only.
        ask = self._asking(text).lower()
        for n in self.nouns:
            if re.search(r"\b%s\b" % re.escape(n), ask):
                return n
        return None

    def declared_answer(self, text):
        a, why = super().declared_answer(text)
        if a is not None:
            t = reader.normalise(text)
            givens, _ = reader.read_givens(t)
            for q in givens:
                if abs(q.v - a["value_si"]) <= 1e-9 * max(1.0, abs(q.v)):
                    return None, "declared: the answer would be a given handed back (%s)" % q.text   # never an echo
        return a, why

    # ---- slot cues for induced faces (the OpenStax run: a geometry 'hypotenuse/leg' face read two POWERS as lengths, and
    # a 'box lifted' potential-energy face was applied to a trampoline). A face's slot cue words are the content words its
    # own template puts right beside each slot; a face is used only when the question says at least one of them.
    def _cues(self, f):
        if not hasattr(f, "_cue_stems"):
            stems = __import__("glue2_v3").stems
            stopw = __import__("glue1_v3").STOP
            cues = set()
            for m in re.finditer(r"\{\d+\}", f.template):
                left = [w for w in re.findall(r"[a-z][a-z\-']+", f.template[:m.start()].lower()) if w not in stopw][-1:]
                right = [w for w in re.findall(r"[a-z][a-z\-']+", f.template[m.end():].lower()) if w not in stopw][:1]
                cues |= set(left) | set(right)
            # the face's output name ("energy" in "the potential energy of a {0} box") names what it gives, not a slot
            f._cue_stems = stems(cues) - stems(self.induced._wh_words(f.template))
        return f._cue_stems

    def _induced_solve(self, text):
        stems = __import__("glue2_v3").stems
        words = __import__("glue1_v3").words
        qw = stems(words(reader.normalise(text)))
        allf = self.induced.faces
        goal = reader.read_goal(reader.normalise(text))
        gdim = goal[1] if goal and goal[0] == "dim" else None

        def needs_cue(f):
            # where the risk was measured: bare-number slots read any dimension, and an intermediate step hands its output
            # on without the question naming it. A final step already answers under the conditions law.
            free = any(s.get("dim") == "free" for s in f.slots)
            final = f.out_kind == "bool" or (f.power is None and f.out_dim == gdim)
            return free or not final
        self.induced.faces = [f for f in allf if not needs_cue(f) or self._cues(f) & qw]
        try:
            r = self._glue_solve(text)
        finally:
            self.induced.faces = allf
        if r.get("status") == "answered":
            for tr in r.get("trace", []):
                terms = [x.strip() for x in str(tr.get("formula", "")).split("×")]
                if any("1/(%s)" % x in terms for x in terms if not x.startswith("1/(")):
                    return {"status": "declined", "reason": "a given cancelled against itself in the arithmetic",
                            "check": "every given used for what it says"}
        return r

    @staticmethod
    def _merge_restated(givens):
        """one fact stated twice ("4.0 km/h (1.1 m/s)", "a 12.0-V system ... a 12.0-V battery") is one quantity: same
        dimension and role, values within 2% -> keep one, preferring the one written in SI units"""
        out = []
        for q in givens:
            twin = next((o for o in out if o.dim == q.dim and o.role == q.role and not q.temp_point
                         and abs(o.v - q.v) <= 0.02 * max(abs(o.v), abs(q.v), 1e-300)), None)
            if twin is None:
                out.append(q)
                continue
            m = re.match(r"\s*-?[\d.,]+\s*-?\s*(.+?)\s*$", q.text)
            u = reader.unit_lookup(m.group(1)) if m else None
            if u and u[0] == 1:                 # the restatement is in SI: keep it instead
                out[out.index(twin)] = q
        return out

    def solve(self, text):
        orig_goal, orig_givens = reader.read_goal, reader.read_givens
        goal = self.goal_of(text)
        reader.read_goal = (lambda t, _g=goal: _g) if goal is not None else orig_goal   # the same goal for both readings

        def read_givens(t):
            g, f = orig_givens(t)
            return self._merge_restated(g), f
        reader.read_givens = read_givens
        try:
            return super().solve(text)
        finally:
            reader.read_goal, reader.read_givens = orig_goal, orig_givens