Mercurial > code > home > repos > homeauto
annotate service/mqtt_to_rdf/inference.py @ 1610:6fc48ef4c696
mysteriously lost an important line
author | drewp@bigasterisk.com |
---|---|
date | Mon, 06 Sep 2021 18:07:28 -0700 |
parents | 34f2817320cc |
children | a794a150a89b |
rev | line source |
---|---|
1587 | 1 """ |
2 copied from reasoning 2021-08-29. probably same api. should | |
3 be able to lib/ this out | |
4 """ | |
1588
0757fafbfdab
WIP inferencer - partial var and function support
drewp@bigasterisk.com
parents:
1587
diff
changeset
|
5 import itertools |
1587 | 6 import logging |
1601 | 7 import time |
1594 | 8 from collections import defaultdict |
9 from dataclasses import dataclass, field | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
10 from typing import Dict, Iterator, List, Set, Tuple, Union, cast |
1588
0757fafbfdab
WIP inferencer - partial var and function support
drewp@bigasterisk.com
parents:
1587
diff
changeset
|
11 |
1587 | 12 from prometheus_client import Summary |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
13 from rdflib import BNode, Graph, Namespace, URIRef |
1589
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
14 from rdflib.graph import ConjunctiveGraph, ReadOnlyGraphAggregate |
1587 | 15 from rdflib.term import Node, Variable |
16 | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
17 from candidate_binding import CandidateBinding |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
18 from inference_types import (BindableTerm, EvaluationFailed, ReadOnlyWorkingSet, Triple) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
19 from lhs_evaluation import Evaluation |
1605 | 20 |
1587 | 21 log = logging.getLogger('infer') |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
22 INDENT = ' ' |
1587 | 23 |
1601 | 24 INFER_CALLS = Summary('read_rules_calls', 'calls') |
1587 | 25 |
26 ROOM = Namespace("http://projects.bigasterisk.com/room/") | |
27 LOG = Namespace('http://www.w3.org/2000/10/swap/log#') | |
28 MATH = Namespace('http://www.w3.org/2000/10/swap/math#') | |
29 | |
1601 | 30 # Graph() makes a BNode if you don't pass |
31 # identifier, which can be a bottleneck. | |
32 GRAPH_ID = URIRef('dont/care') | |
1587 | 33 |
34 | |
1594 | 35 @dataclass |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
36 class Lhs: |
1594 | 37 graph: Graph |
38 | |
39 def __post_init__(self): | |
1608 | 40 # do precomputation in here that's not specific to the workingSet |
41 self.staticRuleStmts = Graph() | |
42 self.lhsBindables: Set[BindableTerm] = set() | |
43 self.lhsBnodes: Set[BNode] = set() | |
1594 | 44 for ruleStmt in self.graph: |
45 varsAndBnodesInStmt = [term for term in ruleStmt if isinstance(term, (Variable, BNode))] | |
46 self.lhsBindables.update(varsAndBnodesInStmt) | |
47 self.lhsBnodes.update(x for x in varsAndBnodesInStmt if isinstance(x, BNode)) | |
48 if not varsAndBnodesInStmt: | |
49 self.staticRuleStmts.add(ruleStmt) | |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
50 |
1602 | 51 self.evaluations = list(Evaluation.findEvals(self.graph)) |
52 | |
1609
34f2817320cc
new tests for a smaller part of the inner loop
drewp@bigasterisk.com
parents:
1608
diff
changeset
|
53 def __repr__(self): |
34f2817320cc
new tests for a smaller part of the inner loop
drewp@bigasterisk.com
parents:
1608
diff
changeset
|
54 return f"Lhs({graphDump(self.graph)})" |
34f2817320cc
new tests for a smaller part of the inner loop
drewp@bigasterisk.com
parents:
1608
diff
changeset
|
55 |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
56 def findCandidateBindings(self, workingSet: ReadOnlyWorkingSet, stats) -> Iterator['BoundLhs']: |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
57 """bindings that fit the LHS of a rule, using statements from workingSet and functions |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
58 from LHS""" |
1597 | 59 log.debug(f'{INDENT*3} nodesToBind: {self.lhsBindables}') |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
60 stats['findCandidateBindingsCalls'] += 1 |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
61 |
1600 | 62 if not self._allStaticStatementsMatch(workingSet): |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
63 stats['findCandidateBindingEarlyExits'] += 1 |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
64 return |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
65 |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
66 for binding in self._possibleBindings(workingSet, stats): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
67 log.debug('') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
68 log.debug(f'{INDENT*4}*trying {binding.binding}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
69 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
70 if not binding.verify(workingSet): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
71 log.debug(f'{INDENT*4} this binding did not verify') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
72 stats['permCountFailingVerify'] += 1 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
73 continue |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
74 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
75 stats['permCountSucceeding'] += 1 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
76 yield binding |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
77 |
1608 | 78 def _allStaticStatementsMatch(self, workingSet: ReadOnlyWorkingSet) -> bool: |
79 for ruleStmt in self.staticRuleStmts: | |
80 if ruleStmt not in workingSet: | |
81 log.debug(f'{INDENT*3} {ruleStmt} not in working set- skip rule') | |
82 return False | |
83 return True | |
84 | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
85 def _possibleBindings(self, workingSet, stats) -> Iterator['BoundLhs']: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
86 """this yields at least the working bindings, and possibly others""" |
1600 | 87 candidateTermMatches: Dict[BindableTerm, Set[Node]] = self._allCandidateTermMatches(workingSet) |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
88 |
1600 | 89 orderedVars, orderedValueSets = _organize(candidateTermMatches) |
90 self._logCandidates(orderedVars, orderedValueSets) | |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
91 |
1597 | 92 log.debug(f'{INDENT*3} trying all permutations:') |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
93 for perm in itertools.product(*orderedValueSets): |
1594 | 94 try: |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
95 yield BoundLhs(self, CandidateBinding(dict(zip(orderedVars, perm)))) |
1594 | 96 except EvaluationFailed: |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
97 stats['permCountFailingEval'] += 1 |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
98 |
1600 | 99 def _allCandidateTermMatches(self, workingSet: ReadOnlyWorkingSet) -> Dict[BindableTerm, Set[Node]]: |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
100 """the total set of terms each variable could possibly match""" |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
101 |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
102 candidateTermMatches: Dict[BindableTerm, Set[Node]] = defaultdict(set) |
1594 | 103 for lhsStmt in self.graph: |
1597 | 104 log.debug(f'{INDENT*4} possibles for this lhs stmt: {lhsStmt}') |
1608 | 105 for i, trueStmt in enumerate(workingSet): |
1597 | 106 # log.debug(f'{INDENT*5} consider this true stmt ({i}): {trueStmt}') |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
107 |
1594 | 108 for v, vals in self._bindingsFromStatement(lhsStmt, trueStmt): |
109 candidateTermMatches[v].update(vals) | |
110 | |
111 for trueStmt in itertools.chain(workingSet, self.graph): | |
112 for b in self.lhsBnodes: | |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
113 for t in [trueStmt[0], trueStmt[2]]: |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
114 if isinstance(t, (URIRef, BNode)): |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
115 candidateTermMatches[b].add(t) |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
116 return candidateTermMatches |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
117 |
1594 | 118 def _bindingsFromStatement(self, stmt1: Triple, stmt2: Triple) -> Iterator[Tuple[Variable, Set[Node]]]: |
119 """if these stmts match otherwise, what BNode or Variable mappings do we learn? | |
120 | |
121 e.g. stmt1=(?x B ?y) and stmt2=(A B C), then we yield (?x, {A}) and (?y, {C}) | |
122 or stmt1=(_:x B C) and stmt2=(A B C), then we yield (_:x, {A}) | |
123 or stmt1=(?x B C) and stmt2=(A B D), then we yield nothing | |
124 """ | |
125 bindingsFromStatement = {} | |
126 for term1, term2 in zip(stmt1, stmt2): | |
127 if isinstance(term1, (BNode, Variable)): | |
128 bindingsFromStatement.setdefault(term1, set()).add(term2) | |
129 elif term1 != term2: | |
130 break | |
131 else: | |
132 for v, vals in bindingsFromStatement.items(): | |
1597 | 133 log.debug(f'{INDENT*5} {v=} {vals=}') |
1594 | 134 yield v, vals |
135 | |
1600 | 136 def _logCandidates(self, orderedVars, orderedValueSets): |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
137 if not log.isEnabledFor(logging.DEBUG): |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
138 return |
1597 | 139 log.debug(f'{INDENT*3} resulting candidate terms:') |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
140 for v, vals in zip(orderedVars, orderedValueSets): |
1597 | 141 log.debug(f'{INDENT*4} {v!r} could be:') |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
142 for val in vals: |
1597 | 143 log.debug(f'{INDENT*5}{val!r}') |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
144 |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
145 |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
146 @dataclass |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
147 class BoundLhs: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
148 lhs: Lhs |
1610 | 149 binding: CandidateBinding |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
150 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
151 def __post_init__(self): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
152 self.usedByFuncs = Graph(identifier=GRAPH_ID) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
153 self._applyFunctions() |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
154 |
1608 | 155 self.graphWithoutEvals = self.lhs.graph - self.usedByFuncs |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
156 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
157 def _applyFunctions(self): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
158 """may grow the binding with some results""" |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
159 while True: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
160 delta = self._applyFunctionsIteration() |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
161 if delta == 0: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
162 break |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
163 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
164 def _applyFunctionsIteration(self): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
165 before = len(self.binding.binding) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
166 delta = 0 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
167 for ev in self.lhs.evaluations: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
168 newBindings, usedGraph = ev.resultBindings(self.binding) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
169 self.usedByFuncs += usedGraph |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
170 self.binding.addNewBindings(newBindings) |
1608 | 171 delta = len(self.binding.binding) - before |
172 log.debug(f'{INDENT*4} eval rules made {delta} new bindings') | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
173 return delta |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
174 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
175 def verify(self, workingSet: ReadOnlyWorkingSet) -> bool: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
176 """Can this bound lhs be true all at once in workingSet?""" |
1608 | 177 boundLhs = list(self.binding.apply(self.lhs.graph)) # leave out statics and evals! |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
178 boundUsedByFuncs = list(self.binding.apply(self.usedByFuncs)) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
179 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
180 self._logVerifyBanner(boundLhs, workingSet, boundUsedByFuncs) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
181 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
182 for stmt in boundLhs: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
183 log.debug(f'{INDENT*4} check for {stmt}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
184 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
185 if stmt in boundUsedByFuncs: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
186 pass |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
187 elif stmt in workingSet: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
188 pass |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
189 else: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
190 log.debug(f'{INDENT*5} stmt not known to be true') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
191 return False |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
192 return True |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
193 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
194 def _logVerifyBanner(self, boundLhs, workingSet: ReadOnlyWorkingSet, boundUsedByFuncs): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
195 if not log.isEnabledFor(logging.DEBUG): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
196 return |
1608 | 197 |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
198 log.debug(f'{INDENT*4}/ verify all bindings against this boundLhs:') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
199 for stmt in sorted(boundLhs): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
200 log.debug(f'{INDENT*4}|{INDENT} {stmt}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
201 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
202 # log.debug(f'{INDENT*4}| and against this workingSet:') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
203 # for stmt in sorted(workingSet): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
204 # log.debug(f'{INDENT*4}|{INDENT} {stmt}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
205 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
206 stmts = sorted(boundUsedByFuncs) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
207 if stmts: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
208 log.debug(f'{INDENT*4}| while ignoring these usedByFuncs:') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
209 for stmt in stmts: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
210 log.debug(f'{INDENT*4}|{INDENT} {stmt}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
211 log.debug(f'{INDENT*4}\\') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
212 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
213 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
214 @dataclass |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
215 class Rule: |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
216 lhsGraph: Graph |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
217 rhsGraph: Graph |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
218 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
219 def __post_init__(self): |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
220 self.lhs = Lhs(self.lhsGraph) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
221 |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
222 |
1587 | 223 class Inference: |
224 | |
225 def __init__(self) -> None: | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
226 self.rules = [] |
1587 | 227 |
228 def setRules(self, g: ConjunctiveGraph): | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
229 self.rules: List[Rule] = [] |
1599
abbf0eb0e640
fix a bug with a slightly moer complicated set of rules
drewp@bigasterisk.com
parents:
1598
diff
changeset
|
230 for stmt in g: |
abbf0eb0e640
fix a bug with a slightly moer complicated set of rules
drewp@bigasterisk.com
parents:
1598
diff
changeset
|
231 if stmt[1] == LOG['implies']: |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
232 self.rules.append(Rule(stmt[0], stmt[2])) |
1599
abbf0eb0e640
fix a bug with a slightly moer complicated set of rules
drewp@bigasterisk.com
parents:
1598
diff
changeset
|
233 # others should go to a default working set? |
1587 | 234 |
1601 | 235 @INFER_CALLS.time() |
1587 | 236 def infer(self, graph: Graph): |
237 """ | |
238 returns new graph of inferred statements. | |
239 """ | |
1597 | 240 log.info(f'{INDENT*0} Begin inference of graph len={graph.__len__()} with rules len={len(self.rules)}:') |
1601 | 241 startTime = time.time() |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
242 stats: Dict[str, Union[int, float]] = defaultdict(lambda: 0) |
1589
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
243 # everything that is true: the input graph, plus every rule conclusion we can make |
1593
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
244 workingSet = Graph() |
b0df43d5494c
big rewrite- more classes, smaller methods, more typesafe, all current tests passing
drewp@bigasterisk.com
parents:
1592
diff
changeset
|
245 workingSet += graph |
1587 | 246 |
1594 | 247 # just the statements that came from RHS's of rules that fired. |
1587 | 248 implied = ConjunctiveGraph() |
249 | |
250 bailout_iterations = 100 | |
251 delta = 1 | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
252 stats['initWorkingSet'] = cast(int, workingSet.__len__()) |
1587 | 253 while delta > 0 and bailout_iterations > 0: |
1597 | 254 log.info(f'{INDENT*1}*iteration ({bailout_iterations} left)') |
1587 | 255 bailout_iterations -= 1 |
256 delta = -len(implied) | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
257 self._iterateAllRules(workingSet, implied, stats) |
1587 | 258 delta += len(implied) |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
259 stats['iterations'] += 1 |
1597 | 260 log.info(f'{INDENT*2} this inference iteration added {delta} more implied stmts') |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
261 stats['timeSpent'] = round(time.time() - startTime, 3) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
262 stats['impliedStmts'] = len(implied) |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
263 log.info(f'{INDENT*0} Inference done {dict(stats)}. Implied:') |
1587 | 264 for st in implied: |
1597 | 265 log.info(f'{INDENT*1} {st}') |
1587 | 266 return implied |
267 | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
268 def _iterateAllRules(self, workingSet: Graph, implied: Graph, stats): |
1589
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
269 for i, r in enumerate(self.rules): |
1600 | 270 self._logRuleApplicationHeader(workingSet, i, r) |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
271 _applyRule(r.lhs, r.rhsGraph, workingSet, implied, stats) |
1587 | 272 |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
273 def _logRuleApplicationHeader(self, workingSet, i, r: Rule): |
1594 | 274 if not log.isEnabledFor(logging.DEBUG): |
275 return | |
276 | |
277 log.debug('') | |
278 log.debug(f'{INDENT*2} workingSet:') | |
1597 | 279 for j, stmt in enumerate(sorted(workingSet)): |
280 log.debug(f'{INDENT*3} ({j}) {stmt}') | |
1594 | 281 |
282 log.debug('') | |
283 log.debug(f'{INDENT*2}-applying rule {i}') | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
284 log.debug(f'{INDENT*3} rule def lhs: {graphDump(r.lhsGraph)}') |
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
285 log.debug(f'{INDENT*3} rule def rhs: {graphDump(r.rhsGraph)}') |
1594 | 286 |
1588
0757fafbfdab
WIP inferencer - partial var and function support
drewp@bigasterisk.com
parents:
1587
diff
changeset
|
287 |
1601 | 288 def _applyRule(lhs: Lhs, rhs: Graph, workingSet: Graph, implied: Graph, stats: Dict): |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
289 for bound in lhs.findCandidateBindings(ReadOnlyGraphAggregate([workingSet]), stats): |
1597 | 290 log.debug(f'{INDENT*3} rule has a working binding:') |
291 | |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
292 for lhsBoundStmt in bound.binding.apply(bound.graphWithoutEvals): |
1597 | 293 log.debug(f'{INDENT*5} adding {lhsBoundStmt=}') |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
294 workingSet.add(lhsBoundStmt) |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
295 for newStmt in bound.binding.apply(rhs): |
1597 | 296 log.debug(f'{INDENT*5} adding {newStmt=}') |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
297 workingSet.add(newStmt) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
298 implied.add(newStmt) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
299 |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
300 |
1590
327202020892
WIP inference- getting into more degenerate test cases
drewp@bigasterisk.com
parents:
1589
diff
changeset
|
301 def graphDump(g: Union[Graph, List[Triple]]): |
327202020892
WIP inference- getting into more degenerate test cases
drewp@bigasterisk.com
parents:
1589
diff
changeset
|
302 if not isinstance(g, Graph): |
1607
b21885181e35
more modules, types. Maybe less repeated computation on BoundLhs
drewp@bigasterisk.com
parents:
1605
diff
changeset
|
303 log.warning(f"it's a {type(g)}") |
1590
327202020892
WIP inference- getting into more degenerate test cases
drewp@bigasterisk.com
parents:
1589
diff
changeset
|
304 g2 = Graph() |
1594 | 305 g2 += g |
1590
327202020892
WIP inference- getting into more degenerate test cases
drewp@bigasterisk.com
parents:
1589
diff
changeset
|
306 g = g2 |
1589
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
307 g.bind('', ROOM) |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
308 g.bind('ex', Namespace('http://example.com/')) |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
309 lines = cast(bytes, g.serialize(format='n3')).decode('utf8').splitlines() |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
310 lines = [line for line in lines if not line.startswith('@prefix')] |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
311 return ' '.join(lines) |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
312 |
5c1055be3c36
WIP more debugging, working towards bnode-matching support
drewp@bigasterisk.com
parents:
1588
diff
changeset
|
313 |
1600 | 314 def _organize(candidateTermMatches: Dict[BindableTerm, Set[Node]]) -> Tuple[List[BindableTerm], List[List[Node]]]: |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
315 items = list(candidateTermMatches.items()) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
316 items.sort() |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
317 orderedVars: List[BindableTerm] = [] |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
318 orderedValueSets: List[List[Node]] = [] |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
319 for v, vals in items: |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
320 orderedVars.append(v) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
321 orderedValues: List[Node] = list(vals) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
322 orderedValues.sort(key=str) |
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
323 orderedValueSets.append(orderedValues) |
1588
0757fafbfdab
WIP inferencer - partial var and function support
drewp@bigasterisk.com
parents:
1587
diff
changeset
|
324 |
1592
d7b66234064b
pure reordering of funcs to make the next diffs smaller
drewp@bigasterisk.com
parents:
1591
diff
changeset
|
325 return orderedVars, orderedValueSets |