Permalink
Browse files

Implemented BDI to all types of knowlede bases, fixed a few bugs

  • Loading branch information...
Markus Schatten
Markus Schatten committed Dec 16, 2013
1 parent 716840b commit 433919e5c234c8eb340be5fd65a681e830122821
Showing with 711 additions and 27 deletions.
  1. +0 −1 spade/Agent.py
  2. +112 −1 spade/ECLiPSeKB.py
  3. +113 −1 spade/Flora2KB.py
  4. +7 −0 spade/SPARQLKB.py
  5. +112 −2 spade/SWIKB.py
  6. +112 −2 spade/XSBKB.py
  7. +3 −1 spade/fipa.py
  8. +66 −17 spade/kb.py
  9. +14 −1 spade/logic.py
  10. +172 −1 test/bdiTestCase.py
View
@@ -1259,7 +1259,6 @@ def registerService(self, service, methodCall=None, otherdf=None):
name = service.getName()
self.DEBUG("Registering RPC service " + name)
self.RPC[name.lower()] = (service, methodCall)
return b.result
def deregisterService(self, DAD, otherdf=None):
View
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from logic import KB
from logic import KB, get_object_type, get_object_instance
from pyxf import eclipse
import random, string
class ECLiPSeKB(KB):
@@ -38,6 +39,116 @@ def loadModule(self, module):
path - path to module'''
self.eclipse.load(module)
def _encode(self, key, value):
'''Encodes a given key value pair to the knowledge base
(internal, for use by kb.KB only)
Usage: instance._encode( key, value )
key - the key (variable name) to be encoded
value - the (Python) value to be encoded'''
if issubclass(value.__class__, str):
self.tell("var('" + key + "','" + value + "', str)")
elif issubclass(value.__class__, int):
self.tell("var('" + key + "'," + str(value) + ", int)")
elif issubclass(value.__class__, float):
self.tell("var('" + key + "', " + str(value) + ", float)")
elif issubclass(value.__class__, list):
listID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
for elem in value:
self._encode(listID, elem)
self.tell("var('" + key + "', '" + listID + "', list)")
elif issubclass(value.__class__, dict):
dictID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
for k, v in value.items():
elemID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
self._encode(elemID + "Key", k)
self._encode(elemID + "Value", v)
self.tell("pair('" + dictID + "','" + elemID + "')")
self.tell("var('" + key + "','" + dictID + "',dict)")
elif value is None:
self.tell("var('" + key + "',none,noneType)")
else:
typ = str( value.__module__ + "." + value.__class__.__name__ )
objID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
if value.__dict__ != {}:
self._encode( objID, value.__dict__ )
else:
self.tell( "pair('" + objID + "', empty_object)" )
self.tell( "var('" + key + "', '" + objID + "', '" + typ + "')" )
def _decode(self, key):
'''Decodes a given key and return its value from the knowledge base
(internal, for use by kb.KB only)
Usage: instance._decode( key )
key - the key (variable name) to be decoded'''
gen = self._gen_decode(key)
try:
return gen.next()
except StopIteration:
return None
def _gen_decode(self, key):
'''Decoding generator
(internal, for use by kb.KB only)
Usage: instance._gen_decode( key )
key - the key (variable name) to be decoded'''
results = self.ask("var('" + key + "', Value, Type)")
if isinstance(results, bool):
yield None
for res in results:
value = str( res["Value"] )
typ = str( res["Type"] )
if typ == "int":
yield int(value)
elif typ == "str":
yield str(value)
elif typ == "float":
yield float(value)
elif typ == "list":
l = []
listID = str(value)
gen = self._gen_decode(listID)
hasElements = True
while hasElements:
try:
l.append(gen.next())
except:
hasElements = False
yield l
elif typ == "dict":
dictID = str(value)
d = {}
for i in self.ask("pair('" + dictID + "', ElemID)"):
elemID = str(i["ElemID"])
if elemID == 'empty_object':
continue
newkey = self._gen_decode(elemID + "Key").next()
newvalue = self._gen_decode(elemID + "Value").next()
d[newkey] = newvalue
yield d
elif typ == "noneType":
yield None
else:
objid = str(key)
res = self.ask("var('" + objid + "', Value, Type)")[0]
classname = res["Type"]
objdict = res["Value"]
try:
module, clas = classname.split(".")
obj = get_object_instance(clas, module)
d = self._gen_decode(objdict).next()
if d == None:
d = {}
obj.__dict__ = d
yield obj
except:
raise GeneratorExit, "No such class in namespace: %s" % classname
if __name__ == '__main__':
kb = ECLiPSeKB()
kb.tell('a(b,c)')
View
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from logic import KB
from logic import KB, get_object_type, get_object_instance
from pyxf import flora2
import random, string
class Flora2KB(KB):
@@ -44,6 +45,117 @@ def loadModule(self, module):
path - path to module'''
self.flora2.load(module)
def _encode(self, key, value):
'''Encodes a given key value pair to the knowledge base
(internal, for use by kb.KB only)
Usage: instance._encode( key, value )
key - the key (variable name) to be encoded
value - the (Python) value to be encoded'''
if issubclass(value.__class__, str):
self.tell("var('" + key + "','" + value + "', str)")
elif issubclass(value.__class__, int):
self.tell("var('" + key + "'," + str(value) + ", int)")
elif issubclass(value.__class__, float):
self.tell("var('" + key + "', " + str(value) + ", float)")
elif issubclass(value.__class__, list):
listID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
for elem in value:
self._encode(listID, elem)
self.tell("var('" + key + "', '" + listID + "', list)")
elif issubclass(value.__class__, dict):
dictID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
for k, v in value.items():
elemID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
self._encode(elemID + "Key", k)
self._encode(elemID + "Value", v)
self.tell("pair('" + dictID + "','" + elemID + "')")
self.tell("var('" + key + "','" + dictID + "',dict)")
elif value is None:
self.tell("var('" + key + "',none,noneType)")
else:
typ = str( value.__module__ + "." + value.__class__.__name__ )
objID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(8))
if value.__dict__ != {}:
self._encode( objID, value.__dict__ )
else:
self.tell( "pair('" + objID + "', empty_object)" )
self.tell( "var('" + key + "', '" + objID + "', '" + typ + "')" )
def _decode(self, key):
'''Decodes a given key and return its value from the knowledge base
(internal, for use by kb.KB only)
Usage: instance._decode( key )
key - the key (variable name) to be decoded'''
gen = self._gen_decode(key)
try:
return gen.next()
except StopIteration:
return None
def _gen_decode(self, key):
'''Decoding generator
(internal, for use by kb.KB only)
Usage: instance._gen_decode( key )
key - the key (variable name) to be decoded'''
results = self.ask("var('" + key + "', ?Value, ?Type)")
if isinstance(results, bool) or results == []:
yield None
for res in results:
value = str( res["Value"] )
typ = str( res["Type"] )
if typ == "int":
yield int(value)
elif typ == "str":
yield str(value)
elif typ == "float":
yield float(value)
elif typ == "list":
l = []
listID = str(value)
gen = self._gen_decode(listID)
hasElements = True
while hasElements:
try:
l.append(gen.next())
except:
hasElements = False
yield l
elif typ == "dict":
dictID = str(value)
d = {}
for i in self.ask("pair('" + dictID + "', ?ElemID)"):
elemID = str(i["ElemID"])
if elemID == 'empty_object':
continue
newkey = self._gen_decode(elemID + "Key").next()
newvalue = self._gen_decode(elemID + "Value").next()
d[newkey] = newvalue
yield d
elif typ == "noneType":
yield None
else:
objid = str(key)
res = self.ask("var('" + objid + "', ?Value, ?Type)")[0]
classname = res["Type"]
objdict = res["Value"]
try:
module, clas = classname.split(".")
obj = get_object_instance(clas, module)
d = self._gen_decode(objdict).next()
if d == None:
d = {}
obj.__dict__ = d
yield obj
except:
raise GeneratorExit, "No such class in namespace: %s" % classname
if __name__ == '__main__':
kb = Flora2KB()
kb.tell('a[ b->c ]')
View
@@ -31,6 +31,13 @@ def retract(self, sentence):
'''Removing triples from RDF store - not implemented'''
raise NotImplementedError('Removing sentences to RDF knowledge bases is not implemented')
def _encode( self, key, value ):
'''Encoding a value in the triple store - not implemented'''
raise NotImplementedError('Encoding values in RDF knowledge bases is not implemented')
def _decode( self, key ):
'''Decoding a value from the triple store - not implemented'''
raise NotImplementedError('Decoding values from RDF knowledge bases is not implemented')
if __name__ == '__main__':
s = SPARQLKB(endpoint='http://lod.openlinksw.com/sparql')
Oops, something went wrong.

0 comments on commit 433919e

Please sign in to comment.