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