knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
knowrob::DataDrivenReasoner Class Referenceabstract

#include <DataDrivenReasoner.h>

Inheritance diagram for knowrob::DataDrivenReasoner:
Collaboration diagram for knowrob::DataDrivenReasoner:

Public Types

enum  Feature {
  NothingSpecial = 1 << 0 , UpdatesItself = 1 << 1 , InvalidatesItself = 1 << 2 , NothingSpecial = 1 << 0 ,
  UpdatesItself = 1 << 1 , InvalidatesItself = 1 << 2
}
 
enum  Feature {
  NothingSpecial = 1 << 0 , UpdatesItself = 1 << 1 , InvalidatesItself = 1 << 2 , NothingSpecial = 1 << 0 ,
  UpdatesItself = 1 << 1 , InvalidatesItself = 1 << 2
}
 

Public Member Functions

 DataDrivenReasoner ()
 
void enableFeature (Feature feature)
 
bool hasFeature (Feature feature) const
 
void setUpdateInterval (double intervalInSeconds)
 
auto updateInterval () const
 
void emit (const std::shared_ptr< reasoner::Event > &event)
 
void observe (const std::shared_ptr< GraphQuery > &query, const BindingsHandler &handler)
 
void observe (const std::string &queryString, const BindingsHandler &handler)
 
virtual void update ()=0
 
virtual void start ()
 
virtual void stop ()
 
 DataDrivenReasoner ()
 
void enableFeature (Feature feature)
 
bool hasFeature (Feature feature) const
 
void setUpdateInterval (double intervalInSeconds)
 
auto updateInterval () const
 
void emit (const std::shared_ptr< reasoner::Event > &event)
 
void observe (const std::shared_ptr< GraphQuery > &query, const BindingsHandler &handler)
 
void observe (const std::string &queryString, const BindingsHandler &handler)
 
virtual void update ()=0
 
virtual void start ()
 
virtual void stop ()
 
- Public Member Functions inherited from knowrob::Reasoner
 Reasoner ()
 
virtual ~Reasoner ()=default
 
auto & reasonerName () const
 
auto reasonerLanguage () const
 
auto storage () const
 
template<class T >
std::shared_ptr< T > getTypedStorage () const
 
ReasonerManagerreasonerManager () const
 
void pushWork (const std::function< void(void)> &fn)
 
void setStorage (const StoragePtr &storage)
 
virtual bool initializeReasoner (const PropertyTree &ptree)=0
 
virtual void unload ()
 
 Reasoner ()
 
virtual ~Reasoner ()=default
 
auto & reasonerName () const
 
auto reasonerLanguage () const
 
auto storage () const
 
template<class T >
std::shared_ptr< T > getTypedStorage () const
 
ReasonerManagerreasonerManager () const
 
void pushWork (const std::function< void(void)> &fn)
 
void setStorage (const StoragePtr &storage)
 
virtual bool initializeReasoner (const PropertyTree &ptree)=0
 
virtual void unload ()
 
- Public Member Functions inherited from knowrob::DataSourceHandler
 DataSourceHandler ()=default
 
virtual ~DataSourceHandler ()=default
 
void addDataHandler (const std::string &format, const DataSourceLoader &fn)
 
bool loadDataSource (const DataSourcePtr &dataSource)
 
bool hasDataHandler (const DataSourcePtr &dataSource) const
 
 DataSourceHandler ()=default
 
virtual ~DataSourceHandler ()=default
 
void addDataHandler (const std::string &format, const DataSourceLoader &fn)
 
bool loadDataSource (const DataSourcePtr &dataSource)
 
bool hasDataHandler (const DataSourcePtr &dataSource) const
 

Protected Member Functions

void processAssertion (const std::vector< TriplePtr > &triples)
 
void processRetraction (const std::vector< TriplePtr > &triples)
 
void processReplacement (const std::vector< TriplePtr > &triples)
 
void processInvalidation ()
 
void setReasonerOrigin (const std::vector< TriplePtr > &triples)
 
void doUpdate ()
 
void queueUpdate ()
 
void processAssertion (const std::vector< TriplePtr > &triples)
 
void processRetraction (const std::vector< TriplePtr > &triples)
 
void processReplacement (const std::vector< TriplePtr > &triples)
 
void processInvalidation ()
 
void setReasonerOrigin (const std::vector< TriplePtr > &triples)
 
void doUpdate ()
 
void queueUpdate ()
 
- Protected Member Functions inherited from knowrob::DataSourceHandler
virtual bool loadDataSourceWithUnknownFormat (const DataSourcePtr &)
 
virtual bool loadDataSourceWithUnknownFormat (const DataSourcePtr &)
 

Protected Attributes

bool isUpdateQueued_ = false
 
bool isRunning_ = false
 
bool isInvalidated_ = true
 
std::chrono::duration< double > updateInterval_ = std::chrono::seconds(1)
 
uint32_t features_ = NothingSpecial
 
std::set< TriplePtrinferredTriples_
 
std::shared_ptr< ThreadPool::RunnerupdateRunner_
 
std::chrono::time_point< std::chrono::high_resolution_clock > lastUpdate_
 
- Protected Attributes inherited from knowrob::DataSourceHandler
std::map< std::string, DataSourceLoaderdataSourceHandler_
 

Detailed Description

A reasoner that is driven by data, i.e., it starts with the data and infers additional knowledge e.g. by applying rules to the data. This is in contrast to a goal-driven reasoner, which is driven by queries. The data is taken from a data backend, which is associated with the reasoner before the reasoner is started.

Definition at line 20 of file DataDrivenReasoner.h.

Member Enumeration Documentation

◆ Feature [1/2]

Features of the reasoner.

Enumerator
NothingSpecial 
UpdatesItself 
InvalidatesItself 
NothingSpecial 
UpdatesItself 
InvalidatesItself 

Definition at line 25 of file DataDrivenReasoner.h.

25  {
26  // The reasoner does not have any special features.
27  NothingSpecial = 1 << 0,
28  // The reasoner updates itself, thus `update` does not need to be called externally.
29  UpdatesItself = 1 << 1,
30  // The reasoner invalidates itself, thus `update` does not need to be called periodically
31  // in case no invalidation happens.
32  InvalidatesItself = 1 << 2
33  };

◆ Feature [2/2]

Features of the reasoner.

Enumerator
NothingSpecial 
UpdatesItself 
InvalidatesItself 
NothingSpecial 
UpdatesItself 
InvalidatesItself 

Definition at line 25 of file DataDrivenReasoner.h.

25  {
26  // The reasoner does not have any special features.
27  NothingSpecial = 1 << 0,
28  // The reasoner updates itself, thus `update` does not need to be called externally.
29  UpdatesItself = 1 << 1,
30  // The reasoner invalidates itself, thus `update` does not need to be called periodically
31  // in case no invalidation happens.
32  InvalidatesItself = 1 << 2
33  };

Constructor & Destructor Documentation

◆ DataDrivenReasoner() [1/2]

DataDrivenReasoner::DataDrivenReasoner ( )

Definition at line 15 of file DataDrivenReasoner.cpp.

15  {
16  using StopChecker = ThreadPool::LambdaRunner::StopChecker;
17  using Runner = ThreadPool::LambdaRunner;
18  updateRunner_ = std::make_shared<Runner>([this](const StopChecker &) { doUpdate(); });
19 }
std::shared_ptr< ThreadPool::Runner > updateRunner_
std::function< bool()> StopChecker
Definition: ThreadPool.h:152

◆ DataDrivenReasoner() [2/2]

knowrob::DataDrivenReasoner::DataDrivenReasoner ( )

Member Function Documentation

◆ doUpdate() [1/2]

void DataDrivenReasoner::doUpdate ( )
protected

Definition at line 43 of file DataDrivenReasoner.cpp.

43  {
44  // do the update
46  // If the reasoner uses Python code, then we must make sure that the GIL is acquired in the current thread.
47  py::gil_lock acquire;
48  update();
49  } else {
50  update();
51  }
53  isUpdateQueued_ = false;
54  isInvalidated_ = false;
55 
57  // if the reasoner does not update itself and does not invalidate itself, then
58  // periodically update the reasoner.
59  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastUpdate_);
60  if (duration > updateInterval_) {
61  // we cannot keep up with the update rate, so directly re-queue the update.
62  queueUpdate();
63  } else {
64  auto remaining = std::chrono::milliseconds(
65  static_cast<int>(updateInterval_.count()) - duration.count());
66  // Create a timer that triggers the update after the remaining time.
67  // It is not optimal to create a new thread for each update though,
68  // but it would be good to stick to the worker thread pool for performing the
69  // update. However, the worker thread pool does not support delayed execution yet.
70  // Note: this is done so to avoid calling sleep for the worker thread
71  // as it would block it from being used for other tasks.
72  std::thread timeout([&remaining, this]() {
73  std::this_thread::sleep_for(remaining);
74  queueUpdate();
75  });
76  timeout.detach();
77  }
78  }
79 
80  lastUpdate_ = now;
81 }
std::chrono::duration< double > updateInterval_
bool hasFeature(Feature feature) const
std::chrono::time_point< std::chrono::high_resolution_clock > lastUpdate_
auto reasonerLanguage() const
Definition: Reasoner.h:42
TimePoint now()
Definition: TimePoint.cpp:12

◆ doUpdate() [2/2]

void knowrob::DataDrivenReasoner::doUpdate ( )
protected

◆ emit() [1/2]

void DataDrivenReasoner::emit ( const std::shared_ptr< reasoner::Event > &  event)

Trigger a reasoner event. This is the main way how the reasoner informs the rest of the system about its result and state.

Parameters
eventa reasoner event.

Definition at line 104 of file DataDrivenReasoner.cpp.

104  {
105  switch (event->eventType()) {
107  processAssertion(std::static_pointer_cast<reasoner::AssertionEvent>(event)->triples());
108  break;
110  processRetraction(std::static_pointer_cast<reasoner::RetractionEvent>(event)->triples());
111  break;
113  processReplacement(std::static_pointer_cast<reasoner::ReplacementEvent>(event)->triples());
114  break;
117  break;
118  }
119 }
void processReplacement(const std::vector< TriplePtr > &triples)
void processAssertion(const std::vector< TriplePtr > &triples)
void processRetraction(const std::vector< TriplePtr > &triples)

◆ emit() [2/2]

void knowrob::DataDrivenReasoner::emit ( const std::shared_ptr< reasoner::Event > &  event)

Trigger a reasoner event. This is the main way how the reasoner informs the rest of the system about its result and state.

Parameters
eventa reasoner event.

◆ enableFeature() [1/2]

void DataDrivenReasoner::enableFeature ( Feature  feature)

Enable a feature of the reasoner.

Parameters
featurea feature.

Definition at line 21 of file DataDrivenReasoner.cpp.

21  {
22  features_ = features_ | static_cast<uint32_t>(feature);
23 }

◆ enableFeature() [2/2]

void knowrob::DataDrivenReasoner::enableFeature ( Feature  feature)

Enable a feature of the reasoner.

Parameters
featurea feature.

◆ hasFeature() [1/2]

bool DataDrivenReasoner::hasFeature ( Feature  feature) const
Returns
true if the reasoner has a feature.

Definition at line 25 of file DataDrivenReasoner.cpp.

25  {
26  return (features_ & static_cast<uint32_t>(feature)) == static_cast<uint32_t>(feature);
27 }

◆ hasFeature() [2/2]

bool knowrob::DataDrivenReasoner::hasFeature ( Feature  feature) const
Returns
true if the reasoner has a feature.

◆ observe() [1/4]

void DataDrivenReasoner::observe ( const std::shared_ptr< GraphQuery > &  query,
const BindingsHandler handler 
)

Observe a graph query. The reasoner will observe the query and call the handler whenever the query's result changes.

Parameters
querya graph query.
handlera bindings handler.

Definition at line 121 of file DataDrivenReasoner.cpp.

121  {
122  reasonerManager().kb()->observe(query, handler);
123 }
ReasonerManager & reasonerManager() const
Definition: Reasoner.cpp:24

◆ observe() [2/4]

void knowrob::DataDrivenReasoner::observe ( const std::shared_ptr< GraphQuery > &  query,
const BindingsHandler handler 
)

Observe a graph query. The reasoner will observe the query and call the handler whenever the query's result changes.

Parameters
querya graph query.
handlera bindings handler.

◆ observe() [3/4]

void DataDrivenReasoner::observe ( const std::string &  queryString,
const BindingsHandler handler 
)

Observe a graph query. The reasoner will observe the query and call the handler whenever the query's result changes.

Parameters
queryStringa graph query string.
handlera bindings handler.

Definition at line 125 of file DataDrivenReasoner.cpp.

125  {
126  auto term = QueryParser::parseGraphTerm(queryString);
127  auto query = std::make_shared<GraphQuery>(term);
128  reasonerManager().kb()->observe(query, handler);
129 }
static std::shared_ptr< GraphTerm > parseGraphTerm(const std::string &queryString)
Definition: QueryParser.cpp:43
TermRule & term()
Definition: terms.cpp:136

◆ observe() [4/4]

void knowrob::DataDrivenReasoner::observe ( const std::string &  queryString,
const BindingsHandler handler 
)

Observe a graph query. The reasoner will observe the query and call the handler whenever the query's result changes.

Parameters
queryStringa graph query string.
handlera bindings handler.

◆ processAssertion() [1/2]

void DataDrivenReasoner::processAssertion ( const std::vector< TriplePtr > &  triples)
protected

Definition at line 148 of file DataDrivenReasoner.cpp.

148  {
149  setReasonerOrigin(triples);
150  reasonerManager().kb()->insertAll(triples);
151 }
void setReasonerOrigin(const std::vector< TriplePtr > &triples)

◆ processAssertion() [2/2]

void knowrob::DataDrivenReasoner::processAssertion ( const std::vector< TriplePtr > &  triples)
protected

◆ processInvalidation() [1/2]

void DataDrivenReasoner::processInvalidation ( )
protected

Definition at line 131 of file DataDrivenReasoner.cpp.

131  {
133  KB_WARN("Reasoner has no feature to invalidate itself, but still generated an invalidation event. Ignoring.");
134  return;
135  }
136  if (!isInvalidated_) {
137  isInvalidated_ = true;
138  queueUpdate();
139  }
140 }
#define KB_WARN
Definition: Logger.h:27

◆ processInvalidation() [2/2]

void knowrob::DataDrivenReasoner::processInvalidation ( )
protected

◆ processReplacement() [1/2]

void DataDrivenReasoner::processReplacement ( const std::vector< TriplePtr > &  triples)
protected

Definition at line 158 of file DataDrivenReasoner.cpp.

158  {
159  setReasonerOrigin(triples);
160 
161  if (inferredTriples_.empty()) {
162  inferredTriples_.insert(triples.begin(), triples.end());
163  reasonerManager().kb()->insertAll(triples);
164  } else {
165  auto &oldTriples = inferredTriples_;
166  // ensure that input triples are sorted which is required for set_difference
167  std::set<TriplePtr> newTriples(triples.begin(), triples.end());
168 
169  std::vector<TriplePtr> triplesToRemove, triplesToAdd;
170  // old inferences without new inferences are the ones that do not hold anymore.
171  std::set_difference(oldTriples.begin(), oldTriples.end(),
172  newTriples.begin(), newTriples.end(),
173  std::inserter(triplesToRemove, triplesToRemove.begin()));
174  // new inferences without old inferences are the ones that are really new.
175  std::set_difference(newTriples.begin(), newTriples.end(),
176  oldTriples.begin(), oldTriples.end(),
177  std::inserter(triplesToAdd, triplesToAdd.begin()));
178  // update the set of inferred triples.
179  for (auto &triple: triplesToRemove) {
180  inferredTriples_.erase(triple);
181  }
182  inferredTriples_.insert(triplesToAdd.begin(), triplesToAdd.end());
183  // update the knowledge base
184  if (!triplesToAdd.empty()) {
185  reasonerManager().kb()->insertAll(triplesToAdd);
186  }
187  if (!triplesToRemove.empty()) {
188  reasonerManager().kb()->removeAll(triplesToRemove);
189  }
190  }
191 }
std::set< TriplePtr > inferredTriples_

◆ processReplacement() [2/2]

void knowrob::DataDrivenReasoner::processReplacement ( const std::vector< TriplePtr > &  triples)
protected

◆ processRetraction() [1/2]

void DataDrivenReasoner::processRetraction ( const std::vector< TriplePtr > &  triples)
protected

Definition at line 153 of file DataDrivenReasoner.cpp.

153  {
154  setReasonerOrigin(triples);
155  reasonerManager().kb()->removeAll(triples);
156 }

◆ processRetraction() [2/2]

void knowrob::DataDrivenReasoner::processRetraction ( const std::vector< TriplePtr > &  triples)
protected

◆ queueUpdate() [1/2]

void DataDrivenReasoner::queueUpdate ( )
protected

Definition at line 33 of file DataDrivenReasoner.cpp.

33  {
34  if (isUpdateQueued_) return;
35  isUpdateQueued_ = true;
36  DefaultThreadPool()->pushWork(
38  [](const std::exception &exc) {
39  KB_ERROR("Error in reasoner update: {}", exc.what());
40  });
41 }
#define KB_ERROR
Definition: Logger.h:28
std::shared_ptr< ThreadPool > DefaultThreadPool()
Definition: ThreadPool.cpp:19

◆ queueUpdate() [2/2]

void knowrob::DataDrivenReasoner::queueUpdate ( )
protected

◆ setReasonerOrigin() [1/2]

void DataDrivenReasoner::setReasonerOrigin ( const std::vector< TriplePtr > &  triples)
protected

Definition at line 142 of file DataDrivenReasoner.cpp.

142  {
143  for (auto &triple: triples) {
144  triple.ptr->setGraph(reasonerName()->stringForm());
145  }
146 }
auto & reasonerName() const
Definition: Reasoner.h:37

◆ setReasonerOrigin() [2/2]

void knowrob::DataDrivenReasoner::setReasonerOrigin ( const std::vector< TriplePtr > &  triples)
protected

◆ setUpdateInterval() [1/2]

void DataDrivenReasoner::setUpdateInterval ( double  intervalInSeconds)

Set the update rate of the reasoner. Only used if update is called externally.

Parameters
intervalInSecondsthe update interval in seconds.

Definition at line 29 of file DataDrivenReasoner.cpp.

29  {
30  updateInterval_ = std::chrono::duration<double>(intervalInSeconds);
31 }

◆ setUpdateInterval() [2/2]

void knowrob::DataDrivenReasoner::setUpdateInterval ( double  intervalInSeconds)

Set the update rate of the reasoner. Only used if update is called externally.

Parameters
intervalInSecondsthe update interval in seconds.

◆ start() [1/2]

void DataDrivenReasoner::start ( )
virtual

Start calling the update function periodically.

Definition at line 83 of file DataDrivenReasoner.cpp.

83  {
84  // Only start if not already running
85  if (isRunning_) return;
86  isRunning_ = true;
87  // update the reasoner if it does not update itself
88  if (!hasFeature(UpdatesItself)) {
89  queueUpdate();
90  }
91 }

◆ start() [2/2]

virtual void knowrob::DataDrivenReasoner::start ( )
virtual

Start calling the update function periodically.

◆ stop() [1/2]

void DataDrivenReasoner::stop ( )
virtual

Stop calling the update function.

Definition at line 93 of file DataDrivenReasoner.cpp.

93  {
94  if (!isRunning_) return;
95  isRunning_ = false;
96  // stop the periodic updating
97  if (!hasFeature(UpdatesItself)) {
98  if (updateRunner_ && !updateRunner_->isTerminated()) {
99  updateRunner_->stop(false);
100  }
101  }
102 }

◆ stop() [2/2]

virtual void knowrob::DataDrivenReasoner::stop ( )
virtual

Stop calling the update function.

◆ update() [1/2]

virtual void knowrob::DataDrivenReasoner::update ( )
pure virtual

Update the reasoner. This function is called periodically to update the reasoner's state in case the reasoner does not update itself (see enableFeature).

◆ update() [2/2]

virtual void knowrob::DataDrivenReasoner::update ( )
pure virtual

Update the reasoner. This function is called periodically to update the reasoner's state in case the reasoner does not update itself (see enableFeature).

◆ updateInterval() [1/2]

auto knowrob::DataDrivenReasoner::updateInterval ( ) const
inline
Returns
the update interval of the reasoner.

Definition at line 58 of file DataDrivenReasoner.h.

58 { return updateInterval_; }

◆ updateInterval() [2/2]

auto knowrob::DataDrivenReasoner::updateInterval ( ) const
inline
Returns
the update interval of the reasoner.

Definition at line 58 of file DataDrivenReasoner.h.

58 { return updateInterval_; }

Member Data Documentation

◆ features_

uint32_t knowrob::DataDrivenReasoner::features_ = NothingSpecial
protected

Definition at line 106 of file DataDrivenReasoner.h.

◆ inferredTriples_

std::set< TriplePtr > knowrob::DataDrivenReasoner::inferredTriples_
protected

Definition at line 107 of file DataDrivenReasoner.h.

◆ isInvalidated_

bool knowrob::DataDrivenReasoner::isInvalidated_ = true
protected

Definition at line 104 of file DataDrivenReasoner.h.

◆ isRunning_

bool knowrob::DataDrivenReasoner::isRunning_ = false
protected

Definition at line 103 of file DataDrivenReasoner.h.

◆ isUpdateQueued_

bool knowrob::DataDrivenReasoner::isUpdateQueued_ = false
protected

Definition at line 102 of file DataDrivenReasoner.h.

◆ lastUpdate_

std::chrono::time_point< std::chrono::high_resolution_clock > knowrob::DataDrivenReasoner::lastUpdate_
protected

Definition at line 109 of file DataDrivenReasoner.h.

◆ updateInterval_

std::chrono::duration< double > knowrob::DataDrivenReasoner::updateInterval_ = std::chrono::seconds(1)
protected

Definition at line 105 of file DataDrivenReasoner.h.

◆ updateRunner_

std::shared_ptr< ThreadPool::Runner > knowrob::DataDrivenReasoner::updateRunner_
protected

Definition at line 108 of file DataDrivenReasoner.h.


The documentation for this class was generated from the following files: