File size: 4,909 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
#!/usr/bin/env python3
"""The Oracle7 kernel, v7: META SWARM round 2, the second-largest hole class (numbers_unread, 7.5% of the census).
Sampled from the pools, the unread numbers were three classes, each fixed in the READER (so the kernel AND the faces it
learns from the specialists' own examples both read them):
  1. number formatting: "2.5 * (10)^(4)", "5 . 0*( 10 )^(5)", "34 . 0º C", "45º" -> ordinary numbers and units;
  2. a number after a quantity noun the formula parts declare DIMENSIONLESS ("refractive index of 1.52", "f-number of
     16", "efficiency of 0.35") -> that quantity, dimensionless, named by its noun (role);
  3. a count: a number before a plural noun or "-tooth"/"-turn" style compound ("2 supporting strands", "18-tooth",
     "500 bacteria") -> a dimensionless count named by its noun (role "count:<noun>").
A named dimensionless quantity or count is never a FREE factor of core arithmetic (the 09-30 law: hidden dimensionless
factors make dimensional analysis a weak filter); only a part whose slot reads it may use it.
usage: module (Kernel7, a drop-in for Kernel6)"""
from __future__ import annotations

import re
import sys

from kernel_v6 import Kernel6
import kernel_v5

reader = kernel_v5.reader
G1 = sys.modules["glue1_v3"]
G2 = sys.modules["glue2_v3"]
_orig_norm, _orig_givens = reader.normalise, reader.read_givens

SCI = [(re.compile(r"(\d)\s*\.\s*(\d)"), r"\1.\2"),                                         # "5 . 0" -> "5.0"
       (re.compile(r"(-?\d[\d.]*)\s*[*x×]\s*\(?\s*10\s*\)?\s*\^\s*\(?\s*(-?\d+)\s*\)?"), r"\1e\2"),   # 2.5 * (10)^(4)
       (re.compile(r"º"), "°"), (re.compile(r"(\d)\s*°\s*([CF])\b"), r"\1 \2")]
COUNT = re.compile(r"(?<![\w.])(\d+)(?:\s*-\s*|\s+)((?:[a-z]+-)?[a-z]+(?:s|tooth|turn|blade|pole|stage))\b", re.I)


def normalise(t):
    t = _orig_norm(t)
    for rx, rep in SCI:
        t = rx.sub(rep, t)
    return t


class Kernel7(Kernel6):
    def __init__(self, *a, **k):
        # the reader is extended BEFORE the faces are learned, so specialists whose own examples use these forms gain faces;
        # the dimensionless nouns come from the formula parts' own declared keys
        from kernel_v1 import Kernel1
        self._dimless_nouns = sorted({n for (n, d) in Kernel1().keys if not any(d)}, key=lambda n: -len(n))
        self._install_reader()
        super().__init__(*a, **k)
        fin = self.induced._finish2
        named = set(self._dimless_nouns)

        def finish2(base, givens, pool, used, goal, trace, hops, path, *rest):
            left = [q for i, q in enumerate(pool) if i not in used and not isinstance(q, tuple)]
            if any(q.dim == reader.DIMLESS and (q.role.startswith("count:") or q.role in named) for q in left):
                return None                     # a count or named ratio is read by a part's slot, never a free factor
            return fin(base, givens, pool, used, goal, trace, hops, path, *rest)
        self.induced._finish2 = finish2

    def declared_answer(self, text):
        t = reader.normalise(text)
        g, _f = reader.read_givens(t)
        for q in g:
            if q.role.startswith("count:") and q.role[6:] not in self.noun_dims:
                return None, "declared: a count no formula part names (%s)" % q.text   # never bound by dimension alone
        return super().declared_answer(text)

    def _install_reader(self):
        kern = self

        def read_givens(t):
            g, flags = _orig_givens(t)
            unread = list(flags.get("unread_numbers") or [])
            if not unread:
                return g, flags
            still = []
            for u in unread:
                q = kern._bind_number(t, str(u))
                if q is None:
                    still.append(u)
                else:
                    g.append(q)
            flags = dict(flags, unread_numbers=still)
            return g, flags
        for mod in (reader, G1, G2):
            if hasattr(mod, "read_givens"):
                mod.read_givens = read_givens
            if hasattr(mod, "normalise"):
                mod.normalise = normalise

    def _bind_number(self, t, u):
        i = t.find(u)
        if i < 0:
            return None
        try:
            v = float(u.replace(",", ""))
        except ValueError:
            return None
        before = re.findall(r"[a-z][a-z\-]*", t[:i].lower())[-6:]
        while before and before[-1] in ("of", "is", "a", "an", "the", "with", "at", "to", "has", "=", "and", "by"):
            before.pop()
        for n in (self._dimless_nouns or []):
            nw = n.split()
            if before[-len(nw):] == nw:
                return reader.Q(v, reader.DIMLESS, u, n)            # a named dimensionless quantity
        m = COUNT.match(t, i)
        if m and m.group(1) == u:
            return reader.Q(v, reader.DIMLESS, m.group(0), "count:" + m.group(2).lower())
        return None