aGrUM  0.20.3
a C++ library for (probabilistic) graphical models
gum::prm::o3prmr::O3prmrInterpreter Class Reference

Represents a O3PRMR context. More...

#include <O3prmrInterpreter.h>

+ Collaboration diagram for gum::prm::o3prmr::O3prmrInterpreter:

Public Member Functions

 O3prmrInterpreter ()
 This constructor create an empty context. More...
 
 ~O3prmrInterpreter ()
 Destructor. Delete current context. More...
 
bool interpretFile (const std::string &filename)
 Interpret the file or the command line. More...
 
bool interpretLine (const std::string &line)
 
const gum::prm::PRM< double > * prm () const
 Retrieve prm object. More...
 
const gum::prm::PRMInference< double > * inference () const
 Retrieve inference motor object. More...
 
const std::vector< QueryResult > & results () const
 Return a vector of QueryResults. Each QueryResults is a struct with query command, time and values, a vector of struct SingleResult, with pair label/value. More...
 
ErrorsContainer errorsContainer () const
 Return container with all errors. More...
 
O3prmrContext< double > * getContext () const
 Getter and setter for the context. More...
 
void setContext (O3prmrContext< double > *context)
 Setter for the context. More...
 
std::vector< std::string > getPaths () const
 Root paths to search from there packages. Default are working dir, request file dir if any and one is calculate from package if any. More...
 
void addPath (std::string path)
 Root paths to search from there packages. Default are './' and one is calculate from request package if any. More...
 
void clearPaths ()
 Root paths to search from there packages. Default are './' and one is calculate from request package if any. More...
 
bool isInSyntaxMode () const
 syntax mode don't process anything, just check syntax. Default is false. More...
 
void setSyntaxMode (bool f)
 syntax mode don't process anything, just check syntax. More...
 
bool isVerboseMode () const
 verbose mode show more details on the program execution. Default is false. More...
 
void setVerboseMode (bool f)
 verbose mode show more details on the program execution. More...
 
Size count () const
 En cas d'échec, l'API de gestion d'erreurs est présente. More...
 
Size errors () const
 

of errors

More...
 
Size warnings () const
 

of warnings

More...
 
ParseError error (Idx i) const
 throw a string error if i >= count More...
 
void showElegantErrors (std::ostream &o=std::cerr) const
 send on std::cerr the list of errors More...
 
void showElegantErrorsAndWarnings (std::ostream &o=std::cerr) const
 send on std::cerr the list of errors or warnings More...
 
void showErrorCounts (std::ostream &o=std::cerr) const
 send on std::cerr the number of errors and the number of warnings More...
 

Detailed Description

Represents a O3PRMR context.

O3prmr use the <double> version of the O3PRM templatized ecosystem

Definition at line 69 of file O3prmrInterpreter.h.

Constructor & Destructor Documentation

◆ O3prmrInterpreter()

gum::prm::o3prmr::O3prmrInterpreter::O3prmrInterpreter ( )

This constructor create an empty context.

Definition at line 53 of file O3prmrInterpreter.cpp.

◆ ~O3prmrInterpreter()

gum::prm::o3prmr::O3prmrInterpreter::~O3prmrInterpreter ( )

Destructor. Delete current context.

Definition at line 59 of file O3prmrInterpreter.cpp.

59  {
60  delete m_context;
61  if (m_bn) { delete m_bn; }
62  for (auto p: m_inf_map) {
63  delete p.second;
64  }
65  delete m_reader->prm();
66  delete m_reader;
67  }
gum::prm::PRM< GUM_SCALAR > * prm()
Definition: O3prmReader.h:107
gum::prm::o3prm::O3prmReader< double > * m_reader
HashTable< const PRMSystem< double > *, PRMInference< double > *> m_inf_map
O3prmrContext< double > * m_context

Member Function Documentation

◆ _readFile_()

std::string gum::prm::o3prmr::O3prmrInterpreter::_readFile_ ( const std::string &  file)
private

Definition at line 176 of file O3prmrInterpreter.cpp.

176  {
177  // read entire file into string
178  std::ifstream istream(file, std::ifstream::binary);
179  if (istream) {
180  // get length of file:
181  istream.seekg(0, istream.end);
182  int length = int(istream.tellg());
183  istream.seekg(0, istream.beg);
184 
185  std::string str;
186  str.resize(length, ' '); // reserve space
187  char* begin = &*str.begin();
188 
189  istream.read(begin, length);
190  istream.close();
191 
192  return str;
193  }
194  GUM_ERROR(OperationNotAllowed, "Could not open file")
195  }
#define GUM_ERROR(type, msg)
Definition: exceptions.h:51

◆ addError()

void gum::prm::o3prmr::O3prmrInterpreter::addError ( std::string  msg)
private

Definition at line 926 of file O3prmrInterpreter.cpp.

926  {
928 
929  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
930  }
std::string toString() const
Return a std::string representation of this gum::ParseError.
ParseError last() const
Returns the last added error.
void addError(const std::string &msg, const std::string &filename, Idx line, Idx col)
Adds an error.
O3prmrContext< double > * m_context

◆ addPath()

void gum::prm::o3prmr::O3prmrInterpreter::addPath ( std::string  path)

Root paths to search from there packages. Default are './' and one is calculate from request package if any.

Definition at line 91 of file O3prmrInterpreter.cpp.

91  {
92  if (path.length() && path.back() != '/') { path = path + '/'; }
93  if (Directory::isDir(path)) {
94  m_paths.push_back(path);
95  } else {
96  GUM_ERROR(NotFound, "not a directory")
97  }
98  }
std::vector< std::string > m_paths
static bool isDir(const std::string &path)
&brief Return true if directory is a valid directory, false otherwise.
Definition: utils_dir.cpp:34
#define GUM_ERROR(type, msg)
Definition: exceptions.h:51

◆ addWarning()

void gum::prm::o3prmr::O3prmrInterpreter::addWarning ( std::string  msg)
private

Definition at line 933 of file O3prmrInterpreter.cpp.

933  {
935 
936  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
937  }
void addWarning(const std::string &msg, const std::string &filename, Idx line, Idx col)
Adds a warning.
std::string toString() const
Return a std::string representation of this gum::ParseError.
ParseError last() const
Returns the last added error.
O3prmrContext< double > * m_context

◆ checkObserve()

bool gum::prm::o3prmr::O3prmrInterpreter::checkObserve ( ObserveCommand< double > *  command)
private

Definition at line 413 of file O3prmrInterpreter.cpp.

413  {
414  try {
415  std::string left_val = command->leftValue;
416  const std::string right_val = command->rightValue;
417 
418  // Contruct the pair (instance,attribut)
419  const PRMSystem< double >& sys = system(left_val);
420  const PRMInstance< double >& instance = sys.get(findInstanceName(left_val, sys));
421  const PRMAttribute< double >& attr = instance.get(findAttributeName(left_val, instance));
422  typename PRMInference< double >::Chain chain = std::make_pair(&instance, &attr);
423 
424  command->system = &sys;
425  command->chain = std::make_pair(&instance, &attr);
426 
427  // Check label exists for this type.
428  // Potential<double> e;
429  command->potentiel.add(chain.second->type().variable());
430  Instantiation i(command->potentiel);
431  bool found = false;
432 
433  for (i.setFirst(); !i.end(); i.inc()) {
434  if (chain.second->type().variable().label(i.val(chain.second->type().variable()))
435  == right_val) {
436  command->potentiel.set(i, (double)1.0);
437  found = true;
438  } else {
439  command->potentiel.set(i, (double)0.0);
440  }
441  }
442 
443  if (!found) addError(right_val + " is not a label of " + left_val);
444 
445  // else command->potentiel = e;
446 
447  return found;
448 
449  } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
450  addError(err);
451  }
452 
453  return false;
454  }
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it&#39;s NodeId in the relational skeleton.
std::string findAttributeName(const std::string &s, const gum::prm::PRMInstance< double > &instance)
std::pair< const PRMInstance< double > *, const PRMAttribute< double > * > Chain
Code alias.
Definition: PRMInference.h:55
const PRMSystem< double > & system(std::string &ident)
std::string findInstanceName(std::string &s, const gum::prm::PRMSystem< double > &sys)

◆ checkQuery()

bool gum::prm::o3prmr::O3prmrInterpreter::checkQuery ( QueryCommand< double > *  command)
private

Definition at line 479 of file O3prmrInterpreter.cpp.

479  {
480  try {
481  std::string name = command->value;
482 
483  // Contruct the pair (instance,attribut)
484  const PRMSystem< double >& sys = system(name);
485  const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
486  const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
487  // PRMInference<double>::Chain chain = std::make_pair(&instance,
488  // &attr);
489 
490  command->system = &sys;
491  command->chain = std::make_pair(&instance, &attr);
492 
493  return true;
494 
495  } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
496  addError(err);
497  }
498 
499  return false;
500  }
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it&#39;s NodeId in the relational skeleton.
std::string findAttributeName(const std::string &s, const gum::prm::PRMInstance< double > &instance)
const PRMSystem< double > & system(std::string &ident)
std::string findInstanceName(std::string &s, const gum::prm::PRMSystem< double > &sys)

◆ checkSemantic()

bool gum::prm::o3prmr::O3prmrInterpreter::checkSemantic ( O3prmrContext< double > *  context)
private

Check semantic validity of context.

Import first all import, and check that systems, instances, attributes and labels exists. While checking, prepare data structures for interpretation. Return true if all is right, false otherwise.

Note : Stop checking at first error unless syntax mode is activated.

Definition at line 296 of file O3prmrInterpreter.cpp.

296  {
297  // Don't parse if any syntax errors.
298  if (errors() > 0) return false;
299 
300  // On importe tous les systèmes.
301  for (const auto command: context->imports()) {
302  m_current_line = command->line;
303  // if import doen't succed stop here unless syntax mode is activated.
304  bool succeed = import(context, command->value);
305 
306  if (!succeed && !isInSyntaxMode()) return false;
307 
308  // En cas de succès, on met à jour le contexte global
309  if (succeed) m_context->addImport(*command);
310  }
311 
312  if (m_verbose)
313  m_log << "## Check semantic for " << context->sessions().size() << " sessions"
314  << std::endl;
315 
316  // On vérifie chaque session
317  for (const auto session: context->sessions()) {
318  std::string sessionName = session->name();
319  O3prmrSession< double >* new_session = new O3prmrSession< double >(sessionName);
320 
321  if (m_verbose)
322  m_log << "## Start session '" << sessionName << "'..." << std::endl << std::endl;
323 
324  for (const auto command: session->commands()) {
325  if (m_verbose)
326  m_log << "# * Going to check command : " << command->toString() << std::endl;
327 
328  // Update the current line (for warnings and errors)
329  m_current_line = command->line;
330 
331  // We check it.
332  bool result = true;
333 
334  try {
335  switch (command->type()) {
337  result = checkSetEngine((SetEngineCommand*)command);
338  break;
339 
341  result = checkSetGndEngine((SetGndEngineCommand*)command);
342  break;
343 
345  result = checkObserve((ObserveCommand< double >*)command);
346  break;
347 
349  result = checkUnobserve((UnobserveCommand< double >*)command);
350  break;
351 
353  result = checkQuery((QueryCommand< double >*)command);
354  break;
355 
356  default:
357  addError("Error : Unknow command : " + command->toString()
358  + "\n -> Command not processed.");
359  result = false;
360  }
361  } catch (Exception& err) {
362  result = false;
363  addError(err.errorContent());
364  } catch (std::string& err) {
365  result = false;
366  addError(err);
367  }
368 
369  // If there was a problem, skip the rest of this session,
370  // unless syntax mode is activated.
371  if (!result && !isInSyntaxMode()) {
372  if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
373 
374  break;
375  }
376 
377  // On l'ajoute au contexte globale
378  if (result) new_session->addCommand((const O3prmrCommand*)command);
379  }
380 
381  // Ajoute la session au contexte global,
382  // ou à la dernière session.
383  if (sessionName == "default" && m_context->sessions().size() > 0)
384  *(m_context->sessions().back()) += *new_session;
385  else
386  m_context->addSession(*new_session);
387 
388  if (m_verbose)
389  m_log << std::endl
390  << "## Session '" << sessionName << "' finished." << std::endl
391  << std::endl
392  << std::endl;
393 
394  // todo : check memory leak
395  // delete new_session; ??
396  }
397 
399 
400  return errors() == 0;
401  }
void addSession(const O3prmrSession< GUM_SCALAR > &session)
bool checkSetEngine(SetEngineCommand *command)
void elegantErrorsAndWarnings(std::ostream &o) const
Print errors on output stream.
bool isVerboseMode() const
verbose mode show more details on the program execution. Default is false.
bool checkSetGndEngine(SetGndEngineCommand *command)
std::vector< ImportCommand *> imports() const
bool checkQuery(QueryCommand< double > *command)
bool checkUnobserve(UnobserveCommand< double > *command)
void addImport(int line, const std::string &import, const std::string &alias)
std::vector< O3prmrSession< GUM_SCALAR > *> sessions() const
bool checkObserve(ObserveCommand< double > *command)
bool isInSyntaxMode() const
syntax mode don&#39;t process anything, just check syntax. Default is false.
void addCommand(const O3prmrCommand *command)
O3prmrContext< double > * m_context

◆ checkSetEngine()

bool gum::prm::o3prmr::O3prmrInterpreter::checkSetEngine ( SetEngineCommand command)
private

Definition at line 403 of file O3prmrInterpreter.cpp.

403  {
404  m_engine = command->value;
405  return m_engine == "SVED" || m_engine == "GRD" || m_engine == "SVE";
406  }

◆ checkSetGndEngine()

bool gum::prm::o3prmr::O3prmrInterpreter::checkSetGndEngine ( SetGndEngineCommand command)
private

Definition at line 408 of file O3prmrInterpreter.cpp.

408  {
409  m_bn_engine = command->value;
410  return m_bn_engine == "VE" || m_bn_engine == "VEBB" || m_bn_engine == "lazy";
411  }

◆ checkUnobserve()

bool gum::prm::o3prmr::O3prmrInterpreter::checkUnobserve ( UnobserveCommand< double > *  command)
private

Definition at line 456 of file O3prmrInterpreter.cpp.

456  {
457  try {
458  std::string name = command->value;
459 
460  // Contruct the pair (instance,attribut)
461  const PRMSystem< double >& sys = system(name);
462  const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
463  const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
464  // PRMInference<double>::Chain chain = std::make_pair(&instance,
465  // &attr);
466 
467  command->system = &sys;
468  command->chain = std::make_pair(&instance, &attr);
469 
470  return true;
471 
472  } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
473  addError(err);
474  }
475 
476  return false;
477  }
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it&#39;s NodeId in the relational skeleton.
std::string findAttributeName(const std::string &s, const gum::prm::PRMInstance< double > &instance)
const PRMSystem< double > & system(std::string &ident)
std::string findInstanceName(std::string &s, const gum::prm::PRMSystem< double > &sys)

◆ clearPaths()

void gum::prm::o3prmr::O3prmrInterpreter::clearPaths ( )

Root paths to search from there packages. Default are './' and one is calculate from request package if any.

Definition at line 102 of file O3prmrInterpreter.cpp.

102 { m_paths.clear(); }
std::vector< std::string > m_paths

◆ count()

Size gum::prm::o3prmr::O3prmrInterpreter::count ( ) const

En cas d'échec, l'API de gestion d'erreurs est présente.

of errors + warnings

Definition at line 889 of file O3prmrInterpreter.cpp.

889 { return m_errors.count(); }
Size count() const
Returns the number of errors and warnings.

◆ error()

ParseError gum::prm::o3prmr::O3prmrInterpreter::error ( Idx  i) const

throw a string error if i >= count

Definition at line 898 of file O3prmrInterpreter.cpp.

898  {
899  if (i >= count()) throw "Index out of bound.";
900 
901  return m_errors.error(i);
902  }
ParseError error(Idx i) const
Returns the i-th error.
Size count() const
En cas d&#39;échec, l&#39;API de gestion d&#39;erreurs est présente.

◆ errors()

Size gum::prm::o3prmr::O3prmrInterpreter::errors ( ) const

of errors

Definition at line 892 of file O3prmrInterpreter.cpp.

892 { return m_errors.error_count; }
Size error_count
Number of errors detected.

◆ errorsContainer()

ErrorsContainer gum::prm::o3prmr::O3prmrInterpreter::errorsContainer ( ) const

Return container with all errors.

Definition at line 905 of file O3prmrInterpreter.cpp.

905 { return m_errors; }

◆ findAttributeName()

std::string gum::prm::o3prmr::O3prmrInterpreter::findAttributeName ( const std::string &  s,
const gum::prm::PRMInstance< double > &  instance 
)
private

Definition at line 696 of file O3prmrInterpreter.cpp.

697  {
698  if (!instance.exists(s))
699  throw "'" + s + "' is not an attribute of instance '" + instance.name() + "'.";
700 
701  return s;
702  }
const std::string & name() const
Returns the name of this object.
Definition: PRMObject_inl.h:34
bool exists(NodeId id) const
Returns true if id matches an PRMAttribute<GUM_SCALAR> in this PRMInstance<GUM_SCALAR>.

◆ findInstanceName()

std::string gum::prm::o3prmr::O3prmrInterpreter::findInstanceName ( std::string &  s,
const gum::prm::PRMSystem< double > &  sys 
)
private

Definition at line 683 of file O3prmrInterpreter.cpp.

684  {
685  // We have found system before, so 's' has been stripped.
686  size_t dot = s.find_first_of('.');
687  std::string name = s.substr(0, dot);
688 
689  if (!sys.exists(name))
690  throw "'" + name + "' is not an instance of system '" + sys.name() + "'.";
691 
692  s = s.substr(dot + 1);
693  return name;
694  }
const std::string & name() const
Returns the name of this object.
Definition: PRMObject_inl.h:34
bool exists(const std::string &name) const
Retruns true either if name is an instance or an array in this PRMSystem.

◆ findSystemName()

std::string gum::prm::o3prmr::O3prmrInterpreter::findSystemName ( std::string &  s)
private

Definition at line 655 of file O3prmrInterpreter.cpp.

655  {
656  size_t dot = s.find_first_of('.');
657  std::string name = s.substr(0, dot);
658 
659  // We look first for real system, next for alias.
660  if (prm()->isSystem(name)) {
661  s = s.substr(dot + 1);
662  return name;
663  }
664 
665  if (!m_context->aliasToImport(name).empty()) {
666  s = s.substr(dot + 1);
667  return m_context->aliasToImport(name);
668  }
669 
670  while (dot != std::string::npos) {
671  if (prm()->isSystem(name)) {
672  s = s.substr(dot + 1);
673  return name;
674  }
675 
676  dot = s.find('.', dot + 1);
677  name = s.substr(0, dot);
678  }
679 
680  throw "could not find any system in '" + s + "'.";
681  }
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
std::string aliasToImport(const std::string &alias)
O3prmrContext< double > * m_context

◆ generateInfEngine()

void gum::prm::o3prmr::O3prmrInterpreter::generateInfEngine ( const gum::prm::PRMSystem< double > &  sys)
private

Definition at line 846 of file O3prmrInterpreter.cpp.

846  {
847  if (m_verbose) m_log << "# Building the inference engine... " << std::flush;
848 
849  //
850  if (m_engine == "SVED") {
851  m_inf = new SVED< double >(*(prm()), sys);
852 
853  //
854  } else if (m_engine == "SVE") {
855  m_inf = new SVE< double >(*(prm()), sys);
856 
857  } else {
858  if (m_engine != "GRD") {
859  addWarning("unkown engine '" + m_engine + "', use GRD insteed.");
860  }
861 
862  MarginalTargetedInference< double >* bn_inf = nullptr;
863  if (m_bn) { delete m_bn; }
864  m_bn = new BayesNet< double >();
865  BayesNetFactory< double > bn_factory(m_bn);
866 
867  if (m_verbose) m_log << "(Grounding the network... " << std::flush;
868 
869  sys.groundedBN(bn_factory);
870 
871  if (m_verbose) m_log << "Finished)" << std::flush;
872 
873  // bn_inf = new LazyPropagation<double>( *m_bn );
874  bn_inf = new VariableElimination< double >(m_bn);
875 
876  auto grd_inf = new GroundedInference< double >(*(prm()), sys);
877  grd_inf->setBNInference(bn_inf);
878  m_inf = grd_inf;
879  }
880 
881  m_inf_map.insert(&sys, m_inf);
882  if (m_verbose) m_log << "Finished." << std::endl;
883  }
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
void groundedBN(BayesNetFactory< GUM_SCALAR > &factory) const
Returns the grounded Bayesian network of this system.
Definition: PRMSystem_tpl.h:88
gum::prm::PRMInference< double > * m_inf
HashTable< const PRMSystem< double > *, PRMInference< double > *> m_inf_map

◆ getContext()

O3prmrContext< double > * gum::prm::o3prmr::O3prmrInterpreter::getContext ( ) const

Getter and setter for the context.

Getter for the context.

Definition at line 73 of file O3prmrInterpreter.cpp.

73 { return m_context; }
O3prmrContext< double > * m_context

◆ getPaths()

std::vector< std::string > gum::prm::o3prmr::O3prmrInterpreter::getPaths ( ) const

Root paths to search from there packages. Default are working dir, request file dir if any and one is calculate from package if any.

Root paths to search from there packages. Default are './' and one is calculate from request package if any.

Definition at line 87 of file O3prmrInterpreter.cpp.

87 { return m_paths; }
std::vector< std::string > m_paths

◆ import()

bool gum::prm::o3prmr::O3prmrInterpreter::import ( O3prmrContext< double > *  context,
std::string  import 
)
private

Definition at line 505 of file O3prmrInterpreter.cpp.

505  {
506  try {
507  if (m_verbose) { m_log << "# Loading system '" << import_name << "' => '" << std::flush; }
508 
509  std::string import_package = import_name;
510 
511  std::replace(import_name.begin(), import_name.end(), '.', '/');
512  import_name += ".o3prm";
513 
514  if (m_verbose) { m_log << import_name << "' ... " << std::endl << std::flush; }
515 
516  std::ifstream file_test;
517  bool found = false;
518  std::string import_abs_filename;
519 
520  // Search in o3prmr file dir.
521  std::string o3prmrFilename = context->filename();
522 
523  if (!o3prmrFilename.empty()) {
524  size_t index = o3prmrFilename.find_last_of('/');
525 
526  if (index != std::string::npos) {
527  std::string dir = o3prmrFilename.substr(0, index + 1);
528  import_abs_filename = dir + import_name;
529 
530  if (m_verbose) {
531  m_log << "# Search from filedir '" << import_abs_filename << "' ... " << std::flush;
532  }
533 
534  file_test.open(import_abs_filename.c_str());
535 
536  if (file_test.is_open()) {
537  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
538 
539  file_test.close();
540  found = true;
541  } else if (m_verbose) {
542  m_log << "not found." << std::endl << std::flush;
543  }
544  }
545  }
546 
547  // Deduce root path from package name.
548  std::string package = context->package();
549 
550  if (!found && !package.empty()) {
551  std::string root;
552 
553  // if filename is not empty, start from it.
554  std::string filename = context->filename();
555 
556  if (!filename.empty()) {
557  size_t size = filename.find_last_of('/');
558 
559  if (size != std::string::npos) {
560  root += filename.substr(0, size + 1); // take with the '/'
561  }
562  }
563 
564  //
565  root += "../";
566  int count = (int)std::count(package.begin(), package.end(), '.');
567 
568  for (int i = 0; i < count; i++)
569  root += "../";
570 
571  import_abs_filename = Directory(root).absolutePath() + import_name;
572 
573  if (m_verbose) {
574  m_log << "# Search from package '" << package << "' => '" << import_abs_filename
575  << "' ... " << std::flush;
576  }
577 
578  file_test.open(import_abs_filename.c_str());
579 
580  if (file_test.is_open()) {
581  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
582 
583  file_test.close();
584  found = true;
585  } else if (m_verbose) {
586  m_log << "not found." << std::endl << std::flush;
587  }
588  }
589 
590  // Search import in all paths.
591  for (const auto& path: m_paths) {
592  import_abs_filename = path + import_name;
593 
594  if (m_verbose) {
595  m_log << "# Search from classpath '" << import_abs_filename << "' ... " << std::flush;
596  }
597 
598  file_test.open(import_abs_filename.c_str());
599 
600  if (file_test.is_open()) {
601  if (m_verbose) { m_log << " found !" << std::endl << std::flush; }
602 
603  file_test.close();
604  found = true;
605  break;
606  } else if (m_verbose) {
607  m_log << " not found." << std::endl << std::flush;
608  }
609  }
610 
611  if (!found) {
612  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
613 
614  addError("import not found.");
615  return false;
616  }
617 
618  // May throw std::IOError if file does't exist
619  Size previousO3prmError = m_reader->errors();
620  Size previousO3prmrError = errors();
621 
622  try {
623  m_reader->readFile(import_abs_filename, import_package);
624 
625  // Show errors and warning
626  if (m_verbose
627  && (m_reader->errors() > (unsigned int)previousO3prmError
628  || errors() > previousO3prmrError)) {
629  m_log << "Finished with errors." << std::endl;
630  } else if (m_verbose) {
631  m_log << "Finished." << std::endl;
632  }
633 
634  } catch (const IOError& err) {
635  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
636 
637  addError(err.errorContent());
638  }
639 
640  // Add o3prm errors and warnings to o3prmr errors
641  for (; previousO3prmError < m_reader->errorsContainer().count(); previousO3prmError++) {
642  m_errors.add(m_reader->errorsContainer().error(previousO3prmError));
643  }
644 
645  return errors() == previousO3prmrError;
646 
647  } catch (const Exception& err) {
648  if (m_verbose) { m_log << "Finished with exceptions." << std::endl; }
649 
650  addError(err.errorContent());
651  return false;
652  }
653  }
Size readFile(const std::string &file, const std::string &module="")
Read file and load its content using a PRMFactory. The package parameter set the file&#39;s content packa...
Size count() const
Returns the number of errors and warnings.
const ErrorsContainer & errorsContainer() const
publishing Errors API
void add(ParseError error)
Add an error object to the container.
gum::prm::o3prm::O3prmReader< double > * m_reader
Size errors() const
publishing Errors API
std::vector< std::string > m_paths
std::string replace(const std::string &s, const std::string &val, const std::string &new_val)
not usable for gcc 4.8 std::vector<std::string> split( const std::string& orig, const std::string& de...
ParseError error(Idx i) const
Returns the i-th error.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:47
Size count() const
En cas d&#39;échec, l&#39;API de gestion d&#39;erreurs est présente.

◆ inference()

const PRMInference< double > * gum::prm::o3prmr::O3prmrInterpreter::inference ( ) const

Retrieve inference motor object.

Definition at line 120 of file O3prmrInterpreter.cpp.

120 { return m_inf; }
gum::prm::PRMInference< double > * m_inf

◆ interpret()

bool gum::prm::o3prmr::O3prmrInterpreter::interpret ( O3prmrContext< double > *  c)
private

Crée le prm correspondant au contexte courant.

Renvoie true en cas de succès, ou false en cas échéant d'échec de l'interprétation du contexte (import introuvable ou non défini, etc).

Definition at line 225 of file O3prmrInterpreter.cpp.

225  {
226  if (isVerboseMode()) m_log << "## Start interpretation." << std::endl << std::flush;
227 
228  // Don't parse if any syntax errors.
229  if (errors() > 0) return false;
230 
231  // For each session
232  std::vector< O3prmrSession< double >* > sessions = c->sessions();
233 
234  for (const auto session: sessions)
235  for (auto command: session->commands()) {
236  // We process it.
237  bool result = true;
238 
239  try {
240  switch (command->type()) {
242  result = observe((ObserveCommand< double >*)command);
243  break;
244 
246  result = unobserve((UnobserveCommand< double >*)command);
247  break;
248 
250  setEngine((SetEngineCommand*)command);
251  break;
252 
254  setGndEngine((SetGndEngineCommand*)command);
255  break;
256 
258  query((QueryCommand< double >*)command);
259  break;
260  }
261  } catch (Exception& err) {
262  result = false;
263  addError(err.errorContent());
264  } catch (std::string& err) {
265  result = false;
266  addError(err);
267  }
268 
269  // If there was a problem, skip the rest of this session,
270  // unless syntax mode is activated.
271  if (!result) {
272  if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
273 
274  break;
275  }
276  }
277 
278  if (isVerboseMode()) m_log << "## End interpretation." << std::endl << std::flush;
279 
280  return errors() == 0;
281  }
bool observe(const ObserveCommand< double > *command)
void query(const QueryCommand< double > *command)
bool isVerboseMode() const
verbose mode show more details on the program execution. Default is false.
std::vector< O3prmrSession< GUM_SCALAR > *> sessions() const
void setGndEngine(const SetGndEngineCommand *command)
void setEngine(const SetEngineCommand *command)
bool unobserve(const UnobserveCommand< double > *command)

◆ interpretFile()

bool gum::prm::o3prmr::O3prmrInterpreter::interpretFile ( const std::string &  filename)

Interpret the file or the command line.

Parse the file or the command line.

If syntax mode is activated, check only syntax and semantic. If errors occured, return false. Errors messages can be retrieve be errorsContainer() methods. If any errors occured, return true. Requests results can be retrieve be results() methods.

If errors occured, return false. Errors messages can be retrieve be getErrorsContainer() methods. If any errors occured, return true. Requests results can be retrieve be results() methods.

Definition at line 134 of file O3prmrInterpreter.cpp.

134  {
135  m_results.clear();
136 
137  try {
138  std::string file_content = _readFile_(filename);
139 
140  delete m_context;
141  m_context = new O3prmrContext< double >(filename);
142  O3prmrContext< double > c(filename);
143 
144  // On vérifie la syntaxe
145  unsigned char* buffer = new unsigned char[file_content.length() + 1];
146  strcpy((char*)buffer, file_content.c_str());
147  Scanner s(buffer, int(file_content.length() + 1));
148  Parser p(&s);
149  p.setO3prmrContext(&c);
150  p.Parse();
151 
152  m_errors = p.errors();
153 
154  if (errors() > 0) { return false; }
155 
156  // Set paths to search from.
157  delete m_reader->prm();
158  delete m_reader;
159  m_reader = new o3prm::O3prmReader< double >();
160 
161  for (size_t i = 0; i < m_paths.size(); i++) {
163  }
164 
165  // On vérifie la sémantique.
166  if (!checkSemantic(&c)) { return false; }
167 
168  if (isInSyntaxMode()) {
169  return true;
170  } else {
171  return interpret(&c);
172  }
173  } catch (gum::Exception&) { return false; }
174  }
std::vector< ParseError > errors
The list of gum::ParseError contained in this gum::ErrorsContainer.
gum::prm::PRM< GUM_SCALAR > * prm()
Definition: O3prmReader.h:107
bool checkSemantic(O3prmrContext< double > *context)
Check semantic validity of context.
gum::prm::o3prm::O3prmReader< double > * m_reader
std::string _readFile_(const std::string &file)
bool interpret(O3prmrContext< double > *c)
Crée le prm correspondant au contexte courant.
Base class for all aGrUM&#39;s exceptions.
Definition: exceptions.h:102
std::vector< std::string > m_paths
void addClassPath(const std::string &class_path)
Add a list of paths to look for o3prm files.
bool isInSyntaxMode() const
syntax mode don&#39;t process anything, just check syntax. Default is false.
std::vector< QueryResult > m_results
O3prmrContext< double > * m_context

◆ interpretLine()

bool gum::prm::o3prmr::O3prmrInterpreter::interpretLine ( const std::string &  line)

Definition at line 197 of file O3prmrInterpreter.cpp.

197  {
198  m_results.clear();
199 
200  // On vérifie la syntaxe
202  Scanner s((unsigned char*)line.c_str(), (int)line.length());
203  Parser p(&s);
204  p.setO3prmrContext(&c);
205  p.Parse();
206  m_errors = p.errors();
207 
208  if (errors() > 0) return false;
209 
210  // On vérifie la sémantique.
211  if (!checkSemantic(&c)) return false;
212 
213  if (isInSyntaxMode())
214  return true;
215  else
216  return interpret(&c);
217  }
std::vector< ParseError > errors
The list of gum::ParseError contained in this gum::ErrorsContainer.
bool checkSemantic(O3prmrContext< double > *context)
Check semantic validity of context.
bool interpret(O3prmrContext< double > *c)
Crée le prm correspondant au contexte courant.
bool isInSyntaxMode() const
syntax mode don&#39;t process anything, just check syntax. Default is false.
std::vector< QueryResult > m_results

◆ isInSyntaxMode()

bool gum::prm::o3prmr::O3prmrInterpreter::isInSyntaxMode ( ) const

syntax mode don't process anything, just check syntax. Default is false.

syntax mode don't process anything, just check syntax.

Definition at line 105 of file O3prmrInterpreter.cpp.

◆ isVerboseMode()

bool gum::prm::o3prmr::O3prmrInterpreter::isVerboseMode ( ) const

verbose mode show more details on the program execution. Default is false.

verbose mode show more details on the program execution.

Definition at line 111 of file O3prmrInterpreter.cpp.

◆ observe()

bool gum::prm::o3prmr::O3prmrInterpreter::observe ( const ObserveCommand< double > *  command)
private

Definition at line 719 of file O3prmrInterpreter.cpp.

719  {
720  const typename PRMInference< double >::Chain& chain = command->chain;
721 
722  // Generate the inference engine if it doesn't exist.
723  if (!m_inf) { generateInfEngine(*(command->system)); }
724 
725  // Prevent from something
726  if (m_inf->hasEvidence(chain)) addWarning(command->leftValue + " is already observed");
727 
728  m_inf->addEvidence(chain, command->potentiel);
729 
730  if (m_verbose)
731  m_log << "# Added evidence " << command->rightValue << " over attribute "
732  << command->leftValue << std::endl;
733 
734  return true;
735 
736  } catch (OperationNotAllowed& ex) {
737  addError("something went wrong when adding evidence " + command->rightValue + " over "
738  + command->leftValue + " : " + ex.errorContent());
739  return false;
740 
741  } catch (const std::string& msg) {
742  addError(msg);
743  return false;
744  }
void generateInfEngine(const gum::prm::PRMSystem< double > &sys)
gum::prm::PRMInference< double > * m_inf
std::pair< const PRMInstance< double > *, const PRMAttribute< double > * > Chain
Code alias.
Definition: PRMInference.h:55
void addEvidence(const Chain &chain, const Potential< GUM_SCALAR > &p)
Add an evidence to the given instance&#39;s elt.
bool hasEvidence(const PRMInstance< GUM_SCALAR > &i) const
Returns true if i has evidence.

◆ prm()

const PRM< double > * gum::prm::o3prmr::O3prmrInterpreter::prm ( ) const

Retrieve prm object.

Definition at line 117 of file O3prmrInterpreter.cpp.

117 { return m_reader->prm(); }
gum::prm::PRM< GUM_SCALAR > * prm()
Definition: O3prmReader.h:107
gum::prm::o3prm::O3prmReader< double > * m_reader

◆ query()

void gum::prm::o3prmr::O3prmrInterpreter::query ( const QueryCommand< double > *  command)
private

Definition at line 769 of file O3prmrInterpreter.cpp.

769  {
770  const std::string& query = command->value;
771 
772  if (m_inf_map.exists(command->system)) {
773  m_inf = m_inf_map[command->system];
774  } else {
775  m_inf = nullptr;
776  }
777 
778  // Create inference engine if it has not been already created.
779  if (!m_inf) { generateInfEngine(*(command->system)); }
780 
781  // Inference
782  if (m_verbose) {
783  m_log << "# Starting inference over query: " << query << "... " << std::endl;
784  }
785 
786  Timer timer;
787  timer.reset();
788 
789  Potential< double > m;
790  m_inf->posterior(command->chain, m);
791 
792  // Compute spent time
793  double t = timer.step();
794 
795  if (m_verbose) { m_log << "Finished." << std::endl; }
796 
797  if (m_verbose) { m_log << "# Time in seconds (accuracy ~0.001): " << t << std::endl; }
798 
799  // Show results
800 
801  if (m_verbose) { m_log << std::endl; }
802 
803  QueryResult result;
804  result.command = query;
805  result.time = t;
806 
807  Instantiation j(m);
808  const PRMAttribute< double >& attr = *(command->chain.second);
809 
810  for (j.setFirst(); !j.end(); j.inc()) {
811  // auto label_value = j.val ( attr.type().variable() );
812  auto label_value = j.val(0);
813  std::string label = attr.type().variable().label(label_value);
814  float value = float(m.get(j));
815 
816  SingleResult singleResult;
817  singleResult.label = label;
818  singleResult.p = value;
819 
820  result.values.push_back(singleResult);
821 
822  if (m_verbose) { m_log << label << " : " << value << std::endl; }
823  }
824 
825  m_results.push_back(result);
826 
827  if (m_verbose) { m_log << std::endl; }
828 
829  } catch (Exception& e) {
830  GUM_SHOWERROR(e);
831  throw "something went wrong while infering: " + e.errorContent();
832 
833  } catch (const std::string& msg) { addError(msg); }
void generateInfEngine(const gum::prm::PRMSystem< double > &sys)
void posterior(const Chain &chain, Potential< GUM_SCALAR > &m)
Compute the posterior of the formal attribute pointed by chain and stores it in m.
DiscreteVariable & variable()
Return a reference on the DiscreteVariable contained in this.
Definition: PRMType_inl.h:44
void query(const QueryCommand< double > *command)
#define GUM_SHOWERROR(e)
Definition: exceptions.h:57
virtual PRMType & type()=0
See gum::PRMClassElement::type().
virtual std::string label(Idx i) const =0
get the indice-th label. This method is pure virtual.
gum::prm::PRMInference< double > * m_inf
HashTable< const PRMSystem< double > *, PRMInference< double > *> m_inf_map
std::vector< QueryResult > m_results

◆ results()

const std::vector< QueryResult > & gum::prm::o3prmr::O3prmrInterpreter::results ( ) const

Return a vector of QueryResults. Each QueryResults is a struct with query command, time and values, a vector of struct SingleResult, with pair label/value.

Return a std::vector of QueryResults. Each QueryResults is a struct with query command, time and values, a std::vector of struct SingleResult, with pair label/value.

Definition at line 125 of file O3prmrInterpreter.cpp.

125 { return m_results; }
std::vector< QueryResult > m_results

◆ setContext()

void gum::prm::o3prmr::O3prmrInterpreter::setContext ( O3prmrContext< double > *  context)

Setter for the context.

Definition at line 76 of file O3prmrInterpreter.cpp.

76  {
77  delete m_context;
78 
79  if (context == 0)
81  else
82  m_context = context;
83  }
O3prmrContext< double > * m_context

◆ setEngine()

void gum::prm::o3prmr::O3prmrInterpreter::setEngine ( const SetEngineCommand command)
private

Definition at line 836 of file O3prmrInterpreter.cpp.

836  {
837  m_engine = command->value;
838  }

◆ setGndEngine()

void gum::prm::o3prmr::O3prmrInterpreter::setGndEngine ( const SetGndEngineCommand command)
private

Definition at line 841 of file O3prmrInterpreter.cpp.

841  {
842  m_bn_engine = command->value;
843  }

◆ setSyntaxMode()

void gum::prm::o3prmr::O3prmrInterpreter::setSyntaxMode ( bool  f)

syntax mode don't process anything, just check syntax.

Definition at line 108 of file O3prmrInterpreter.cpp.

◆ setVerboseMode()

void gum::prm::o3prmr::O3prmrInterpreter::setVerboseMode ( bool  f)

verbose mode show more details on the program execution.

Definition at line 114 of file O3prmrInterpreter.cpp.

◆ showElegantErrors()

void gum::prm::o3prmr::O3prmrInterpreter::showElegantErrors ( std::ostream &  o = std::cerr) const

send on std::cerr the list of errors

Definition at line 908 of file O3prmrInterpreter.cpp.

908  {
910  }
void elegantErrors(std::ostream &o) const
Print errors on output stream.

◆ showElegantErrorsAndWarnings()

void gum::prm::o3prmr::O3prmrInterpreter::showElegantErrorsAndWarnings ( std::ostream &  o = std::cerr) const

send on std::cerr the list of errors or warnings

Definition at line 913 of file O3prmrInterpreter.cpp.

913  {
915  }
void elegantErrorsAndWarnings(std::ostream &o) const
Print errors on output stream.

◆ showErrorCounts()

void gum::prm::o3prmr::O3prmrInterpreter::showErrorCounts ( std::ostream &  o = std::cerr) const

send on std::cerr the number of errors and the number of warnings

Definition at line 918 of file O3prmrInterpreter.cpp.

918  {
920  }
void syntheticResults(std::ostream &o) const
Print errors on output stream.

◆ system()

const PRMSystem< double > & gum::prm::o3prmr::O3prmrInterpreter::system ( std::string &  ident)
private

Definition at line 705 of file O3prmrInterpreter.cpp.

705  {
706  try {
707  return prm()->getSystem(findSystemName(ident));
708  } catch (const std::string&) {}
709 
710  if ((m_context->mainImport() != 0) && prm()->isSystem(m_context->mainImport()->value))
711  return prm()->getSystem(m_context->mainImport()->value);
712 
713  throw "could not find any system or alias in '" + ident
714  + "' and no default alias has been set.";
715  }
const ImportCommand * mainImport() const
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
std::string findSystemName(std::string &s)
bool isSystem(const std::string &name) const
Definition: PRM_tpl.h:88
PRMSystem< GUM_SCALAR > & getSystem(const std::string &name)
Returns a constant reference on a PRMSystem<GUM_SCALAR> given it&#39;s name.
Definition: PRM_tpl.h:140
O3prmrContext< double > * m_context

◆ unobserve()

bool gum::prm::o3prmr::O3prmrInterpreter::unobserve ( const UnobserveCommand< double > *  command)
private

Definition at line 748 of file O3prmrInterpreter.cpp.

748  {
749  std::string name = command->value;
750  typename PRMInference< double >::Chain chain = command->chain;
751 
752  // Prevent from something
753  if (!m_inf || !m_inf->hasEvidence(chain)) {
754  addWarning(name + " was not observed");
755  } else {
756  m_inf->removeEvidence(chain);
757 
758  if (m_verbose) m_log << "# Removed evidence over attribute " << name << std::endl;
759  }
760 
761  return true;
762 
763  } catch (const std::string& msg) {
764  addError(msg);
765  return false;
766  }
gum::prm::PRMInference< double > * m_inf
std::pair< const PRMInstance< double > *, const PRMAttribute< double > * > Chain
Code alias.
Definition: PRMInference.h:55
void removeEvidence(const Chain &chain)
Remove evidence on the given instance&#39;s elt.
bool hasEvidence(const PRMInstance< GUM_SCALAR > &i) const
Returns true if i has evidence.

◆ warnings()

Size gum::prm::o3prmr::O3prmrInterpreter::warnings ( ) const

of warnings

Definition at line 895 of file O3prmrInterpreter.cpp.

Member Data Documentation

◆ m_bn

gum::BayesNet< double >* gum::prm::o3prmr::O3prmrInterpreter::m_bn
private

Definition at line 168 of file O3prmrInterpreter.h.

◆ m_bn_engine

std::string gum::prm::o3prmr::O3prmrInterpreter::m_bn_engine
private

Definition at line 173 of file O3prmrInterpreter.h.

◆ m_context

O3prmrContext< double >* gum::prm::o3prmr::O3prmrInterpreter::m_context
private

Definition at line 165 of file O3prmrInterpreter.h.

◆ m_current_line

int gum::prm::o3prmr::O3prmrInterpreter::m_current_line
private

Definition at line 179 of file O3prmrInterpreter.h.

◆ m_engine

std::string gum::prm::o3prmr::O3prmrInterpreter::m_engine
private

Definition at line 172 of file O3prmrInterpreter.h.

◆ m_errors

gum::ErrorsContainer gum::prm::o3prmr::O3prmrInterpreter::m_errors
private

Definition at line 175 of file O3prmrInterpreter.h.

◆ m_inf

gum::prm::PRMInference< double >* gum::prm::o3prmr::O3prmrInterpreter::m_inf
private

Definition at line 170 of file O3prmrInterpreter.h.

◆ m_inf_map

HashTable< const PRMSystem< double >*, PRMInference< double >* > gum::prm::o3prmr::O3prmrInterpreter::m_inf_map
private

Definition at line 171 of file O3prmrInterpreter.h.

◆ m_log

std::ostream& gum::prm::o3prmr::O3prmrInterpreter::m_log
private

Definition at line 178 of file O3prmrInterpreter.h.

◆ m_paths

std::vector< std::string > gum::prm::o3prmr::O3prmrInterpreter::m_paths
private

Definition at line 167 of file O3prmrInterpreter.h.

◆ m_reader

gum::prm::o3prm::O3prmReader< double >* gum::prm::o3prmr::O3prmrInterpreter::m_reader
private

Definition at line 166 of file O3prmrInterpreter.h.

◆ m_results

std::vector< QueryResult > gum::prm::o3prmr::O3prmrInterpreter::m_results
private

Definition at line 174 of file O3prmrInterpreter.h.

◆ m_syntax_flag

bool gum::prm::o3prmr::O3prmrInterpreter::m_syntax_flag
private

Definition at line 176 of file O3prmrInterpreter.h.

◆ m_verbose

bool gum::prm::o3prmr::O3prmrInterpreter::m_verbose
private

Definition at line 177 of file O3prmrInterpreter.h.


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