pykb reference#

pykb is a Python wrapper around the KnowledgeCore ROS API. It offers an idomatic Python interface to the robot’s knowledge base.

Complete usage example#

import rospy
import time
from knowledge_core.api import KB

REASONING_DELAY = 0.1 # sec

rospy.init_node("test_knowledge_base")

kb = KB()

def onevent(evt):
    print("Something happened! %s" % evt)


kb += ["alfred rdf:type Human", "alfred likes icecream"]

if 'alfred' in kb:
    print("Hello Alfred!")

if 'alfred likes icecream' in kb:
    print("Oh, you like icrecreams?")

kb -= ["alfred likes icecream"]

if 'alfred likes *' not in kb:
    print("You don't like anything? what a pity...")

kb += ["Human rdfs:subClassOf Animal"]
time.sleep(REASONING_DELAY) # give some time to the reasoner

if 'alfred rdf:type Animal' in kb:
    print("I knew it!")

for facts in kb.about("Human"):
    print(facts)

for known_human in kb["?human rdf:type Human"]:
    print(known_human)


kb += ["alfred desires jump", "alfred desires oil"]
kb += ["jump rdf:type Action"]

for action_lover in kb["?agent desires ?obj", "?obj rdf:type Action"]:
    print(action_lover)

kb.subscribe(["?agent isIn ?loc", "?loc rdf:type Room"], onevent)
kb += ["alfred isIn sleepingroom", "sleepingroom rdf:type Room"]

time.sleep(1) # event should have been triggered!

API#

class knowledge_core.api.KB#

Bases: object

__contains__(pattern)#

This will return ‘True’ is either a concept - described by its ID or label- or a statement or a set of statement is present (or can be infered) in the ontology.

This allows syntax like:

if 'Toto' in kb:
    #...
if 'toto sees tata' in kb:
    #...
__getitem__(*args)#

This method introduces a different way of querying the ontology server. It uses the args (be it a string or a set of strings) to find concepts that match the pattern. An optional ‘models’ parameter can be given to specify the list of models the query is executed on.

Depending on the argument, 4 differents behaviours are possible:

  • with a string that can not be lexically split into 3 tokens (ie, a string that do not look like a s p o tuple), a lookup is performed, and matching resource are returned

  • with a single s p o pattern:
    • if only one of s, p, o is an unbound variable, returns the list of resources matching this pattern.

    • if 2 or 3 of the tokens are unbound variables (like kb["* * *"] or kb["* rdf:type *"]), a list of statements matching the pattern is returned.

  • with a list of patterns, a list of dictionaries is returned with possible combination of values for the different variables. For instance, kb[["?agent desires ?action", "?action rdf:type Jump"]] would return something like: [{"agent":"james", "action": "jumpHigh"}, {"agent": "laurel", "action":"jumpHigher"}]

Attention: if more than one argument is passed, and if the last argument is a list, this list is used as the set of models to execute the query on. If not such list is provided, the query is executed on all models.

Use example:

import kb

kb = KB()

for agent in kb["* rdf:type Agent"]:
    #...

if kb["* livesIn ?house", "?house isIn toulouse", ['GERALD']]:
    #...

#Assuming 'toulouse' has label "ville rose":
city_id = kb["ville rose"]
__iadd__(stmts)#

This method allows to easily add new statements to the ontology with the += operator. It can only add statement to the default robot’s model (other agents’ model are not accessible).

kb = KB(<host>, <port>)
kb += "toto likes icecream"
kb += ["toto loves tata", "tata rdf:type Robot"]
__isub__(stmts)#

This method allows to easily retract statements from the ontology with the -= operator. It can only add statement to the robot’s model (other agents’ model are not accessible). If a statement doesn’t exist, it is silently skipped.

kb = KB(<host>, <port>)
kb -= "toto likes icecream"
kb -= ["toto loves tata", "tata rdf:type Robot"]
about(term, models=[])#

See KnowledgeCore API documentation.

add(stmts, models=[], lifespan=0)#

See KnowledgeCore API documentation.

clear()#

See KnowledgeCore API documentation.

exist(pattern, models=[])#

See KnowledgeCore API documentation.

find(patterns, vars=[], models=[])#

See KnowledgeCore API documentation.

hello()#

See KnowledgeCore API documentation.

lookup(query, models=[])#

See KnowledgeCore API documentation.

remove(stmts, models=[])#

See KnowledgeCore API documentation.

revise(stmts, policy)#

See KnowledgeCore API documentation.

stats()#

See KnowledgeCore API documentation.

subscribe(pattern, callback, one_shot=False, models=None)#

Allows to subscribe to an event, and get notified when the event is triggered.

>>> def onevent(evt):
>>>     print("In callback. Got evt %s" % evt)
>>>
>>> self.kb.subscribe(["?o isIn room"], onevent)
>>> self.kb += ["alfred isIn room"]
>>> # 'onevent' get called
In callback. Got evt [u'alfred']

The ‘var’ parameter can be used with the ‘NEW_INSTANCE’ type of event to tell which variable must be returned.

The ‘models’ parameter allows for registering an event in a specific list of models. By default, the pattern is monitored on every models.

Returns the event id of the newly created event.

update(stmts, models=[], lifespan=0)#

See KnowledgeCore API documentation.

exception knowledge_core.api.KbError(value)#

Bases: Exception