predicate indexing before pattern matching.

main
bog 2024-04-29 23:15:06 +02:00
parent 6a4c31d401
commit d44b14e159
2 changed files with 50 additions and 16 deletions

View File

@ -4,10 +4,10 @@ import fol
class Kb:
def __init__(self):
self.base = []
self.indexes = {}
self.counter = fol.cnf.Counter()
def make_f(self, h):
f = h
if type(f) is str:
f = fol.p(f)
@ -90,18 +90,28 @@ class Kb:
def clause_in(self, clause, lst):
for other in lst:
same = clause.equals(other)
s = fol.unify(clause, other)
# same = s is not None
if same:
return True
return False
def tell(self, request):
req = self.make_f(request)
def add_req(self, req):
if len(req) == 1:
preds = []
for r in req:
preds.extend(r.find_by_name('PRED'))
for p in preds:
if p.value in self.indexes.keys():
self.indexes[p.value].append(req)
else:
self.indexes[p.value] = [req]
self.check_request(req)
self.base.append(req)
def tell(self, request):
req = self.make_f(request)
self.add_req(req)
def ask(self, request):
while True:
n = len(self.base)
@ -129,12 +139,23 @@ class Kb:
conclusion = self.conclusion(rule)
solution = []
solutions = []
self.solve(rule, self.conds(rule), self.facts, solution, solutions)
preds = []
for cond in self.conds(rule):
preds.append(cond.value)
facts = []
for p in preds:
if p in self.indexes.keys():
facts.extend(self.indexes[p])
facts = [f[0] for f in facts]
self.solve(rule, self.conds(rule), facts, solution, solutions)
for sol in solutions:
concl = conclusion.subst(sol)
if not self.exists(concl) and concl.depth() < 4:
self.base.append([concl])
if concl.depth() < 8 and not self.exists(concl):
self.add_req([concl])
return
def merge_substs(self, substs):

View File

@ -3,16 +3,29 @@ import fol
if __name__ == '__main__':
kb = fol.kb.Kb()
try:
if False:
kb.tell('Est(ALICE, X0, S0)')
kb.tell('Proche(X0, X1)')
kb.tell('Proche(X1, X2)')
kb.tell('Proche(X2, X3)')
kb.tell('Proche(X3, X4)')
if True:
kb.tell('Est(ALICE, L0, S0)')
kb.tell('Proche(L0, L1)')
kb.tell('Proche(L1, L2)')
kb.tell('Proche(L2, L3)')
kb.tell('Proche(L3, L4)')
kb.tell('(Est(ALICE, x, s) & Proche(x, y)) -> Poss(go(x, y), s)')
kb.tell('Poss(go(x, y), s) -> Est(ALICE, y, do(go(x, y), s))')
answer = kb.ask('Est(ALICE, x, y)')
print(answer)
if False:
print(f'{len(kb.base)}----------------')
[print(r) for r in kb.base]
print(f'{len(kb.base)}----------------')
print(answer)
if False:
for k, v in kb.indexes.items():
print('--------', k, '--------')
[print(p) for p in v]
else:
kb.tell('Friend(ALICE, BOB)')
kb.tell('Friend(BOB, CLAIRE)')