aGrUM  0.14.1
O3prmrInterpreter.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005 by Christophe GONZALES and Pierre-Henri WUILLEMIN *
3  * {prenom.nom}_at_lip6.fr *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the *
17  * Free Software Foundation, Inc., *
18  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19  ***************************************************************************/
27 #include <agrum/agrum.h>
28 
29 #include <agrum/BN/BayesNet.h>
33 
38 
39 #include <agrum/PRM/o3prmr/cocoR/Parser.h>
40 
41 namespace gum {
42 
43  namespace prm {
44 
45  namespace o3prmr {
46 
47  /* **************************************************************************
48  */
49 
52  m_context(new O3prmrContext< double >()),
53  m_reader(new o3prm::O3prmReader< double >()), m_bn(0), m_inf(0),
54  m_syntax_flag(false), m_verbose(false), m_log(std::cout),
55  m_current_line(-1) {}
56 
59  delete m_context;
60  if (m_bn) { delete m_bn; }
61  for (auto p : m_inf_map) {
62  delete p.second;
63  }
64  delete m_reader->prm();
65  delete m_reader;
66  }
67 
68  /* **************************************************************************
69  */
70 
73  return m_context;
74  }
75 
78  delete m_context;
79 
80  if (context == 0)
82  else
83  m_context = context;
84  }
85 
88  std::vector< std::string > O3prmrInterpreter::getPaths() const {
89  return m_paths;
90  }
91 
94  void O3prmrInterpreter::addPath(std::string path) {
95  if (path.length() && path.back() != '/') { path = path + '/'; }
96  if (Directory::isDir(path)) {
97  m_paths.push_back(path);
98  } else {
99  GUM_ERROR(NotFound, "not a directory");
100  }
101  }
102 
106 
109 
112 
115 
118 
121  return m_reader->prm();
122  }
123 
126  return m_inf;
127  }
128 
132  const std::vector< QueryResult >& O3prmrInterpreter::results() const {
133  return m_results;
134  }
135 
143  bool O3prmrInterpreter::interpretFile(const std::string& filename) {
144  m_results.clear();
145 
146  try {
147  std::string file_content = __readFile(filename);
148 
149  delete m_context;
150  m_context = new O3prmrContext< double >(filename);
151  O3prmrContext< double > c(filename);
152 
153  // On vérifie la syntaxe
154  unsigned char* buffer = new unsigned char[file_content.length() + 1];
155  strcpy((char*)buffer, file_content.c_str());
156  Scanner s(buffer, int(file_content.length() + 1));
157  Parser p(&s);
158  p.setO3prmrContext(&c);
159  p.Parse();
160 
161  m_errors = p.errors();
162 
163  if (errors() > 0) { return false; }
164 
165  // Set paths to search from.
166  delete m_reader->prm();
167  delete m_reader;
169 
170  for (size_t i = 0; i < m_paths.size(); i++) {
172  }
173 
174  // On vérifie la sémantique.
175  if (!checkSemantic(&c)) { return false; }
176 
177  if (isInSyntaxMode()) {
178  return true;
179  } else {
180  return interpret(&c);
181  }
182  } catch (gum::Exception&) { return false; }
183  }
184 
185  std::string O3prmrInterpreter::__readFile(const std::string& file) {
186  // read entire file into string
187  std::ifstream istream(file, std::ifstream::binary);
188  if (istream) {
189  // get length of file:
190  istream.seekg(0, istream.end);
191  int length = int(istream.tellg());
192  istream.seekg(0, istream.beg);
193 
194  std::string str;
195  str.resize(length, ' '); // reserve space
196  char* begin = &*str.begin();
197 
198  istream.read(begin, length);
199  istream.close();
200 
201  return str;
202  }
203  GUM_ERROR(OperationNotAllowed, "Could not open file");
204  }
205 
206  bool O3prmrInterpreter::interpretLine(const std::string& line) {
207  m_results.clear();
208 
209  // On vérifie la syntaxe
211  Scanner s((unsigned char*)line.c_str(), (int)line.length());
212  Parser p(&s);
213  p.setO3prmrContext(&c);
214  p.Parse();
215  m_errors = p.errors();
216 
217  if (errors() > 0) return false;
218 
219  // On vérifie la sémantique.
220  if (!checkSemantic(&c)) return false;
221 
222  if (isInSyntaxMode())
223  return true;
224  else
225  return interpret(&c);
226  }
227 
235  if (isVerboseMode())
236  m_log << "## Start interpretation." << std::endl << std::flush;
237 
238  // Don't parse if any syntax errors.
239  if (errors() > 0) return false;
240 
241  // For each session
242  std::vector< O3prmrSession< double >* > sessions = c->sessions();
243 
244  for (const auto session : sessions)
245  for (auto command : session->commands()) {
246  // We process it.
247  bool result = true;
248 
249  try {
250  switch (command->type()) {
252  result = observe((ObserveCommand< double >*)command);
253  break;
254 
256  result = unobserve((UnobserveCommand< double >*)command);
257  break;
258 
260  setEngine((SetEngineCommand*)command);
261  break;
262 
265  break;
266 
268  query((QueryCommand< double >*)command);
269  break;
270  }
271  } catch (Exception& err) {
272  result = false;
273  addError(err.errorContent());
274  } catch (std::string& err) {
275  result = false;
276  addError(err);
277  }
278 
279  // If there was a problem, skip the rest of this session,
280  // unless syntax mode is activated.
281  if (!result) {
282  if (m_verbose)
283  m_log << "Errors : skip the rest of this session." << std::endl;
284 
285  break;
286  }
287  }
288 
289  if (isVerboseMode())
290  m_log << "## End interpretation." << std::endl << std::flush;
291 
292  return errors() == 0;
293  }
294 
295  /* **************************************************************************
296  */
297 
309  // Don't parse if any syntax errors.
310  if (errors() > 0) return false;
311 
312  // On importe tous les systèmes.
313  for (const auto command : context->imports()) {
314  m_current_line = command->line;
315  // if import doen't succed stop here unless syntax mode is activated.
316  bool succeed = import(context, command->value);
317 
318  if (!succeed && !isInSyntaxMode()) return false;
319 
320  // En cas de succès, on met à jour le contexte global
321  if (succeed) m_context->addImport(*command);
322  }
323 
324  if (m_verbose)
325  m_log << "## Check semantic for " << context->sessions().size()
326  << " sessions" << std::endl;
327 
328  // On vérifie chaque session
329  for (const auto session : context->sessions()) {
330  std::string sessionName = session->name();
331  O3prmrSession< double >* new_session =
332  new O3prmrSession< double >(sessionName);
333 
334  if (m_verbose)
335  m_log << "## Start session '" << sessionName << "'..." << std::endl
336  << std::endl;
337 
338  for (const auto command : session->commands()) {
339  if (m_verbose)
340  m_log << "# * Going to check command : " << command->toString()
341  << std::endl;
342 
343  // Update the current line (for warnings and errors)
344  m_current_line = command->line;
345 
346  // We check it.
347  bool result = true;
348 
349  try {
350  switch (command->type()) {
352  result = checkSetEngine((SetEngineCommand*)command);
353  break;
354 
356  result = checkSetGndEngine((SetGndEngineCommand*)command);
357  break;
358 
360  result = checkObserve((ObserveCommand< double >*)command);
361  break;
362 
364  result = checkUnobserve((UnobserveCommand< double >*)command);
365  break;
366 
368  result = checkQuery((QueryCommand< double >*)command);
369  break;
370 
371  default:
372  addError("Error : Unknow command : " + command->toString()
373  + "\n -> Command not processed.");
374  result = false;
375  }
376  } catch (Exception& err) {
377  result = false;
378  addError(err.errorContent());
379  } catch (std::string& err) {
380  result = false;
381  addError(err);
382  }
383 
384  // If there was a problem, skip the rest of this session,
385  // unless syntax mode is activated.
386  if (!result && !isInSyntaxMode()) {
387  if (m_verbose)
388  m_log << "Errors : skip the rest of this session." << std::endl;
389 
390  break;
391  }
392 
393  // On l'ajoute au contexte globale
394  if (result) new_session->addCommand((const O3prmrCommand*)command);
395  }
396 
397  // Ajoute la session au contexte global,
398  // ou à la dernière session.
399  if (sessionName == "default" && m_context->sessions().size() > 0)
400  *(m_context->sessions().back()) += *new_session;
401  else
402  m_context->addSession(*new_session);
403 
404  if (m_verbose)
405  m_log << std::endl
406  << "## Session '" << sessionName << "' finished." << std::endl
407  << std::endl
408  << std::endl;
409 
410  // todo : check memory leak
411  // delete new_session; ??
412  }
413 
414  if (isVerboseMode() && errors() != 0)
416 
417  return errors() == 0;
418  }
419 
421  m_engine = command->value;
422  return m_engine == "SVED" || m_engine == "GRD" || m_engine == "SVE";
423  }
424 
426  m_bn_engine = command->value;
427  return m_bn_engine == "VE" || m_bn_engine == "VEBB"
428  || m_bn_engine == "lazy";
429  }
430 
432  try {
433  std::string left_val = command->leftValue;
434  const std::string right_val = command->rightValue;
435 
436  // Contruct the pair (instance,attribut)
437  const PRMSystem< double >& sys = system(left_val);
438  const PRMInstance< double >& instance =
439  sys.get(findInstanceName(left_val, sys));
440  const PRMAttribute< double >& attr =
441  instance.get(findAttributeName(left_val, instance));
442  typename PRMInference< double >::Chain chain =
443  std::make_pair(&instance, &attr);
444 
445  command->system = &sys;
446  command->chain = std::make_pair(&instance, &attr);
447 
448  // Check label exists for this type.
449  // Potential<double> e;
450  command->potentiel.add(chain.second->type().variable());
451  Instantiation i(command->potentiel);
452  bool found = false;
453 
454  for (i.setFirst(); !i.end(); i.inc()) {
455  if (chain.second->type().variable().label(
456  i.val(chain.second->type().variable()))
457  == right_val) {
458  command->potentiel.set(i, (double)1.0);
459  found = true;
460  } else {
461  command->potentiel.set(i, (double)0.0);
462  }
463  }
464 
465  if (!found) addError(right_val + " is not a label of " + left_val);
466 
467  // else command->potentiel = e;
468 
469  return found;
470 
471  } catch (Exception& err) {
472  addError(err.errorContent());
473  } catch (std::string& err) { addError(err); }
474 
475  return false;
476  }
477 
479  try {
480  std::string name = command->value;
481 
482  // Contruct the pair (instance,attribut)
483  const PRMSystem< double >& sys = system(name);
484  const PRMInstance< double >& instance =
485  sys.get(findInstanceName(name, sys));
486  const PRMAttribute< double >& attr =
487  instance.get(findAttributeName(name, instance));
488  // PRMInference<double>::Chain chain = std::make_pair(&instance,
489  // &attr);
490 
491  command->system = &sys;
492  command->chain = std::make_pair(&instance, &attr);
493 
494  return true;
495 
496  } catch (Exception& err) {
497  addError(err.errorContent());
498  } catch (std::string& err) { addError(err); }
499 
500  return false;
501  }
502 
504  try {
505  std::string name = command->value;
506 
507  // Contruct the pair (instance,attribut)
508  const PRMSystem< double >& sys = system(name);
509  const PRMInstance< double >& instance =
510  sys.get(findInstanceName(name, sys));
511  const PRMAttribute< double >& attr =
512  instance.get(findAttributeName(name, instance));
513  // PRMInference<double>::Chain chain = std::make_pair(&instance,
514  // &attr);
515 
516  command->system = &sys;
517  command->chain = std::make_pair(&instance, &attr);
518 
519  return true;
520 
521  } catch (Exception& err) {
522  addError(err.errorContent());
523  } catch (std::string& err) { addError(err); }
524 
525  return false;
526  }
527 
528  // Import the system o3prm file
529  // Return false if any error.
530 
532  std::string import_name) {
533  try {
534  if (m_verbose) {
535  m_log << "# Loading system '" << import_name << "' => '" << std::flush;
536  }
537 
538  std::string import_package = import_name;
539 
540  std::replace(import_name.begin(), import_name.end(), '.', '/');
541  import_name += ".o3prm";
542 
543  if (m_verbose) {
544  m_log << import_name << "' ... " << std::endl << std::flush;
545  }
546 
547  std::ifstream file_test;
548  bool found = false;
549  std::string import_abs_filename;
550 
551  // Search in o3prmr file dir.
552  std::string o3prmrFilename = context->filename();
553 
554  if (!o3prmrFilename.empty()) {
555  size_t index = o3prmrFilename.find_last_of('/');
556 
557  if (index != std::string::npos) {
558  std::string dir = o3prmrFilename.substr(0, index + 1);
559  import_abs_filename = dir + import_name;
560 
561  if (m_verbose) {
562  m_log << "# Search from filedir '" << import_abs_filename
563  << "' ... " << std::flush;
564  }
565 
566  file_test.open(import_abs_filename.c_str());
567 
568  if (file_test.is_open()) {
569  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
570 
571  file_test.close();
572  found = true;
573  } else if (m_verbose) {
574  m_log << "not found." << std::endl << std::flush;
575  }
576  }
577  }
578 
579  // Deduce root path from package name.
580  std::string package = context->package();
581 
582  if (!found && !package.empty()) {
583  std::string root;
584 
585  // if filename is not empty, start from it.
586  std::string filename = context->filename();
587 
588  if (!filename.empty()) {
589  size_t size = filename.find_last_of('/');
590 
591  if (size != std::string::npos) {
592  root += filename.substr(0, size + 1); // take with the '/'
593  }
594  }
595 
596  //
597  root += "../";
598  int count = (int)std::count(package.begin(), package.end(), '.');
599 
600  for (int i = 0; i < count; i++)
601  root += "../";
602 
603  import_abs_filename = Directory(root).absolutePath() + import_name;
604 
605  if (m_verbose) {
606  m_log << "# Search from package '" << package << "' => '"
607  << import_abs_filename << "' ... " << std::flush;
608  }
609 
610  file_test.open(import_abs_filename.c_str());
611 
612  if (file_test.is_open()) {
613  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
614 
615  file_test.close();
616  found = true;
617  } else if (m_verbose) {
618  m_log << "not found." << std::endl << std::flush;
619  }
620  }
621 
622  // Search import in all paths.
623  for (const auto& path : m_paths) {
624  import_abs_filename = path + import_name;
625 
626  if (m_verbose) {
627  m_log << "# Search from classpath '" << import_abs_filename
628  << "' ... " << std::flush;
629  }
630 
631  file_test.open(import_abs_filename.c_str());
632 
633  if (file_test.is_open()) {
634  if (m_verbose) { m_log << " found !" << std::endl << std::flush; }
635 
636  file_test.close();
637  found = true;
638  break;
639  } else if (m_verbose) {
640  m_log << " not found." << std::endl << std::flush;
641  }
642  }
643 
644  if (!found) {
645  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
646 
647  addError("import not found.");
648  return false;
649  }
650 
651  // May throw std::IOError if file does't exist
652  Size previousO3prmError = m_reader->errors();
653  Size previousO3prmrError = errors();
654 
655  try {
656  m_reader->readFile(import_abs_filename, import_package);
657 
658  // Show errors and warning
659  if (m_verbose
660  && (m_reader->errors() > (unsigned int)previousO3prmError
661  || errors() > previousO3prmrError)) {
662  m_log << "Finished with errors." << std::endl;
663  } else if (m_verbose) {
664  m_log << "Finished." << std::endl;
665  }
666 
667  } catch (const IOError& err) {
668  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
669 
670  addError(err.errorContent());
671  }
672 
673  // Add o3prm errors and warnings to o3prmr errors
674  for (; previousO3prmError < m_reader->errorsContainer().count();
675  previousO3prmError++) {
676  m_errors.add(m_reader->errorsContainer().error(previousO3prmError));
677  }
678 
679  return errors() == previousO3prmrError;
680 
681  } catch (const Exception& err) {
682  if (m_verbose) { m_log << "Finished with exceptions." << std::endl; }
683 
684  addError(err.errorContent());
685  return false;
686  }
687  }
688 
689  std::string O3prmrInterpreter::findSystemName(std::string& s) {
690  size_t dot = s.find_first_of('.');
691  std::string name = s.substr(0, dot);
692 
693  // We look first for real system, next for alias.
694  if (prm()->isSystem(name)) {
695  s = s.substr(dot + 1);
696  return name;
697  }
698 
699  if (!m_context->aliasToImport(name).empty()) {
700  s = s.substr(dot + 1);
701  return m_context->aliasToImport(name);
702  }
703 
704  while (dot != std::string::npos) {
705  if (prm()->isSystem(name)) {
706  s = s.substr(dot + 1);
707  return name;
708  }
709 
710  dot = s.find('.', dot + 1);
711  name = s.substr(0, dot);
712  }
713 
714  throw "could not find any system in '" + s + "'.";
715  }
716 
717  std::string
719  const PRMSystem< double >& sys) {
720  // We have found system before, so 's' has been stripped.
721  size_t dot = s.find_first_of('.');
722  std::string name = s.substr(0, dot);
723 
724  if (!sys.exists(name))
725  throw "'" + name + "' is not an instance of system '" + sys.name()
726  + "'.";
727 
728  s = s.substr(dot + 1);
729  return name;
730  }
731 
733  const std::string& s, const PRMInstance< double >& instance) {
734  if (!instance.exists(s))
735  throw "'" + s + "' is not an attribute of instance '" + instance.name()
736  + "'.";
737 
738  return s;
739  }
740 
741  // After this method, ident doesn't contains the system name anymore.
742  const PRMSystem< double >& O3prmrInterpreter::system(std::string& ident) {
743  try {
744  return prm()->getSystem(findSystemName(ident));
745  } catch (const std::string&) {}
746 
747  if ((m_context->mainImport() != 0)
749  return prm()->getSystem(m_context->mainImport()->value);
750 
751  throw "could not find any system or alias in '" + ident
752  + "' and no default alias has been set.";
753  }
754 
756 
757  bool
759  const typename PRMInference< double >::Chain& chain = command->chain;
760 
761  // Generate the inference engine if it doesn't exist.
762  if (!m_inf) { generateInfEngine(*(command->system)); }
763 
764  // Prevent from something
765  if (m_inf->hasEvidence(chain))
766  addWarning(command->leftValue + " is already observed");
767 
768  m_inf->addEvidence(chain, command->potentiel);
769 
770  if (m_verbose)
771  m_log << "# Added evidence " << command->rightValue << " over attribute "
772  << command->leftValue << std::endl;
773 
774  return true;
775 
776  } catch (OperationNotAllowed& ex) {
777  addError("something went wrong when adding evidence " + command->rightValue
778  + " over " + command->leftValue + " : " + ex.errorContent());
779  return false;
780 
781  } catch (const std::string& msg) {
782  addError(msg);
783  return false;
784  }
785 
787 
789  const UnobserveCommand< double >* command) try {
790  std::string name = command->value;
791  typename PRMInference< double >::Chain chain = command->chain;
792 
793  // Prevent from something
794  if (!m_inf || !m_inf->hasEvidence(chain)) {
795  addWarning(name + " was not observed");
796  } else {
797  m_inf->removeEvidence(chain);
798 
799  if (m_verbose)
800  m_log << "# Removed evidence over attribute " << name << std::endl;
801  }
802 
803  return true;
804 
805  } catch (const std::string& msg) {
806  addError(msg);
807  return false;
808  }
809 
812  const std::string& query = command->value;
813 
814  if (m_inf_map.exists(command->system)) {
815  m_inf = m_inf_map[command->system];
816  } else {
817  m_inf = nullptr;
818  }
819 
820  // Create inference engine if it has not been already created.
821  if (!m_inf) { generateInfEngine(*(command->system)); }
822 
823  // Inference
824  if (m_verbose) {
825  m_log << "# Starting inference over query: " << query << "... "
826  << std::endl;
827  }
828 
829  Timer timer;
830  timer.reset();
831 
833  m_inf->marginal(command->chain, m);
834 
835  // Compute spent time
836  double t = timer.step();
837 
838  if (m_verbose) { m_log << "Finished." << std::endl; }
839 
840  if (m_verbose) {
841  m_log << "# Time in seconds (accuracy ~0.001): " << t << std::endl;
842  }
843 
844  // Show results
845 
846  if (m_verbose) { m_log << std::endl; }
847 
848  QueryResult result;
849  result.command = query;
850  result.time = t;
851 
852  Instantiation j(m);
853  const PRMAttribute< double >& attr = *(command->chain.second);
854 
855  for (j.setFirst(); !j.end(); j.inc()) {
856  // auto label_value = j.val ( attr.type().variable() );
857  auto label_value = j.val(0);
858  std::string label = attr.type().variable().label(label_value);
859  float value = float(m.get(j));
860 
861  SingleResult singleResult;
862  singleResult.label = label;
863  singleResult.p = value;
864 
865  result.values.push_back(singleResult);
866 
867  if (m_verbose) { m_log << label << " : " << value << std::endl; }
868  }
869 
870  m_results.push_back(result);
871 
872  if (m_verbose) { m_log << std::endl; }
873 
874  } catch (Exception& e) {
875  GUM_SHOWERROR(e);
876  throw "something went wrong while infering: " + e.errorContent();
877 
878  } catch (const std::string& msg) { addError(msg); }
879 
882  m_engine = command->value;
883  }
884 
887  m_bn_engine = command->value;
888  }
889 
892  if (m_verbose)
893  m_log << "# Building the inference engine... " << std::flush;
894 
895  //
896  if (m_engine == "SVED") {
897  m_inf = new SVED< double >(*(prm()), sys);
898 
899  //
900  } else if (m_engine == "SVE") {
901  m_inf = new SVE< double >(*(prm()), sys);
902 
903  } else {
904  if (m_engine != "GRD") {
905  addWarning("unkown engine '" + m_engine + "', use GRD insteed.");
906  }
907 
908  MarginalTargetedInference< double >* bn_inf = nullptr;
909  if (m_bn) { delete m_bn; }
910  m_bn = new BayesNet< double >();
911  BayesNetFactory< double > bn_factory(m_bn);
912 
913  if (m_verbose) m_log << "(Grounding the network... " << std::flush;
914 
915  sys.groundedBN(bn_factory);
916 
917  if (m_verbose) m_log << "Finished)" << std::flush;
918 
919  // bn_inf = new LazyPropagation<double>( *m_bn );
920  bn_inf = new VariableElimination< double >(m_bn);
921 
922  auto grd_inf = new GroundedInference< double >(*(prm()), sys);
923  grd_inf->setBNInference(bn_inf);
924  m_inf = grd_inf;
925  }
926 
927  m_inf_map.insert(&sys, m_inf);
928  if (m_verbose) m_log << "Finished." << std::endl;
929  }
930 
931  /* **************************************************************************
932  */
933 
936 
939 
942 
945  if (i >= count()) throw "Index out of bound.";
946 
947  return m_errors.error(i);
948  }
949 
952  return m_errors;
953  }
954 
956  void O3prmrInterpreter::showElegantErrors(std::ostream& o) const {
958  }
959 
963  }
964 
966  void O3prmrInterpreter::showErrorCounts(std::ostream& o) const {
968  }
969 
970  /* **************************************************************************
971  */
972 
974  void O3prmrInterpreter::addError(std::string msg) {
976 
977  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
978  }
979 
981  void O3prmrInterpreter::addWarning(std::string msg) {
983 
984  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
985  }
986 
987  } // namespace o3prmr
988  } // namespace prm
989 } // namespace gum
void showElegantErrors(std::ostream &o=std::cerr) const
send on std::cerr the list of errors
aGrUM&#39;s Potential is a multi-dimensional array with tensor operators.
Definition: potential.h:57
const PRMSystem< GUM_SCALAR > * system
bool observe(const ObserveCommand< double > *command)
void addPath(std::string path)
Root paths to search from there packages. Default are &#39;./&#39; and one is calculate from request package ...
void generateInfEngine(const gum::prm::PRMSystem< double > &sys)
Cross-platform directory utility.
Definition: utils_dir.h:59
Potential< GUM_SCALAR > potentiel
const ImportCommand * mainImport() const
void addSession(const O3prmrSession< GUM_SCALAR > &session)
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
double step() const
Returns the delta time between now and the last reset() call (or the constructor).
Definition: timer_inl.h:39
DiscreteVariable & variable()
Return a reference on the DiscreteVariable contained in this.
Definition: PRMType_inl.h:42
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...
PRMAttribute< GUM_SCALAR > & get(NodeId id)
Getter on an PRMAttribute<GUM_SCALAR> of this PRMInstance<GUM_SCALAR>.
void query(const QueryCommand< double > *command)
void addWarning(const std::string &msg, const std::string &filename, Idx line, Idx col)
Adds a warning.
const std::string & name() const
Returns the name of this object.
Definition: PRMObject_inl.h:32
Size count() const
Returns the number of errors and warnings.
virtual GUM_SCALAR get(const Instantiation &i) const final
Default implementation of MultiDimContainer::get().
bool checkSetEngine(SetEngineCommand *command)
const PRMSystem< GUM_SCALAR > * system
Headers of GroundedInference.
Size error_count
Number of errors detected.
#define GUM_SHOWERROR(e)
Definition: exceptions.h:58
virtual PRMType & type()=0
See gum::PRMClassElement::type().
An PRMInstance is a Bayesian Network fragment defined by a Class and used in a PRMSystem.
Definition: PRMInstance.h:60
PRMInference< GUM_SCALAR >::Chain chain
std::vector< ParseError > errors
The list of gum::ParseError contained in this gum::ErrorsContainer.
gum::prm::PRM< GUM_SCALAR > * prm()
Definition: O3prmReader.h:108
bool checkSemantic(O3prmrContext< double > *context)
Check semantic validity of context.
STL namespace.
This class is used to represent parsing errors for the different parser implemented in aGrUM...
bool exists(NodeId id) const
Returns true if id matches an PRMAttribute<GUM_SCALAR> in this PRMInstance<GUM_SCALAR>.
<agrum/BN/inference/variableElimination.h>
const ErrorsContainer & errorsContainer() const
publishing Errors API
void syntheticResults(std::ostream &o) const
Print errors on output stream.
Class representing Bayesian networks.
void elegantErrorsAndWarnings(std::ostream &o) const
Print errors on output stream.
void add(ParseError error)
Add an error object to the container.
bool isVerboseMode() const
verbose mode show more details on the program execution. Default is false.
This class is used contain and manipulate gum::ParseError.
bool checkSetGndEngine(SetGndEngineCommand *command)
<agrum/BN/inference/marginalTargetedInference.h>
std::vector< ImportCommand *> imports() const
const gum::prm::PRMInference< double > * inference() const
Retrieve inference motor object.
gum is the global namespace for all aGrUM entities
Definition: agrum.h:25
std::string toString() const
Return a std::string representation of this gum::ParseError.
bool checkQuery(QueryCommand< double > *command)
Implementation of a variable elimination algorithm for inference in Bayesian Networks.
std::string aliasToImport(const std::string &alias)
bool checkUnobserve(UnobserveCommand< double > *command)
std::string findSystemName(std::string &s)
Idx val(Idx i) const
Returns the current value of the variable at position i.
void addImport(int line, const std::string &import, const std::string &alias)
void marginal(const Chain &chain, Potential< GUM_SCALAR > &m)
Compute the marginal of the formal attribute pointed by chain and stores it in m. ...
gum::prm::o3prm::O3prmReader< double > * m_reader
void reset()
Reset the timer.
Definition: timer_inl.h:29
Headers of SVED (Structured Value Elimination with d-seperation).
const PRMSystem< GUM_SCALAR > * system
void showElegantErrorsAndWarnings(std::ostream &o=std::cerr) const
send on std::cerr the list of errors or warnings
Size errors() const
publishing Errors API
ParseError error(Idx i) const
throw a string error if i >= count
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it&#39;s NodeId in the relational skeleton.
void inc()
Operator increment.
std::string toString() const
bool import(O3prmrContext< double > *context, std::string import)
virtual std::string label(Idx i) const =0
get the indice-th label. This method is pure virtual.
void groundedBN(BayesNetFactory< GUM_SCALAR > &factory) const
Returns the grounded Bayesian Network of this system.
Definition: PRMSystem_tpl.h:79
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
Definition: SVED.h:60
std::vector< SingleResult > values
bool isSystem(const std::string &name) const
Definition: PRM_tpl.h:86
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:143
This file contains abstract class definitions for Bayesian networks inference classes.
bool interpret(O3prmrContext< double > *c)
Crée le prm correspondant au contexte courant.
Base class for all aGrUM&#39;s exceptions.
Definition: exceptions.h:103
PRMInference< GUM_SCALAR >::Chain chain
std::string findAttributeName(const std::string &s, const gum::prm::PRMInstance< double > &instance)
void elegantErrors(std::ostream &o) const
Print errors on output stream.
gum::prm::PRMInference< double > * m_inf
std::vector< std::string > m_paths
bool interpretLine(const std::string &line)
void clearPaths()
Root paths to search from there packages. Default are &#39;./&#39; and one is calculate from request package ...
void addClassPath(const std::string &class_path)
Add a list of paths to look for o3prm files.
void setSyntaxMode(bool f)
syntax mode don&#39;t process anything, just check syntax.
This is an abstract class.
Definition: O3prmrContext.h:48
Class for assigning/browsing values to tuples of discrete variables.
Definition: instantiation.h:80
ErrorsContainer errorsContainer() const
Return container with all errors.
bool interpretFile(const std::string &filename)
Interpret the file or the command line.
Represent a o3prmr context, with an import, and some sequencials commands.
std::vector< O3prmrSession< GUM_SCALAR > *> sessions() const
bool checkObserve(ObserveCommand< double > *command)
bool exists(const std::string &name) const
Retruns true either if name is an instance or an array in this PRMSystem.
std::string absolutePath() const
Returns directory absolute path.
Definition: utils_dir.cpp:88
Headers of O3prmInterpreter.
void setGndEngine(const SetGndEngineCommand *command)
void setFirst()
Assign the first values to the tuple of the Instantiation.
void addEvidence(const Chain &chain, const Potential< GUM_SCALAR > &p)
Add an evidence to the given instance&#39;s elt.
void setEngine(const SetEngineCommand *command)
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...
static bool isDir(const std::string &path)
&brief Return true if directory is a valid directory, false otherwise.
Definition: utils_dir.cpp:32
Class used to compute response times for benchmark purposesThis class represents a classic timer...
Definition: timer.h:48
Size Idx
Type for indexes.
Definition: types.h:50
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...
~O3prmrInterpreter()
Destructor. Delete current context.
ParseError error(Idx i) const
Returns the i-th error.
bool unobserve(const UnobserveCommand< double > *command)
Implementation of a Shafer-Shenoy&#39;s-like version of lazy propagation for inference in Bayesian Networ...
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:45
bool isInSyntaxMode() const
syntax mode don&#39;t process anything, just check syntax. Default is false.
O3prmrContext< double > * getContext() const
Getter and setter for the context.
void showErrorCounts(std::ostream &o=std::cerr) const
send on std::cerr the number of errors and the number of warnings
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.
Size count() const
En cas d&#39;échec, l&#39;API de gestion d&#39;erreurs est présente.
PRMInference< GUM_SCALAR >::Chain chain
const std::string errorContent() const
Returns the message content.
Definition: exceptions.h:132
std::string __readFile(const std::string &file)
ParseError last() const
Returns the last added error.
HashTable< const PRMSystem< double > *, PRMInference< double > *> m_inf_map
void addError(const std::string &msg, const std::string &filename, Idx line, Idx col)
Adds an error.
const PRMSystem< double > & system(std::string &ident)
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.
void setContext(O3prmrContext< double > *context)
Setter for the context.
#define GUM_ERROR(type, msg)
Definition: exceptions.h:52
<agrum/PRM/groundedInference.h>
Headers of SVE (Structured Variable Elimination).
This class is an implementation of the Structured Variable Elimination algorithm on PRM<GUM_SCALAR>...
Definition: SVE.h:63
A factory class to ease BayesNet construction.
Definition: BayesNet.h:43
O3prmrInterpreter()
This constructor create an empty context.
bool end() const
Returns true if the Instantiation reached the end.
std::vector< QueryResult > m_results
std::string findInstanceName(std::string &s, const gum::prm::PRMSystem< double > &sys)
void setVerboseMode(bool f)
verbose mode show more details on the program execution.
void addCommand(const O3prmrCommand *command)
O3prmrContext< double > * m_context