aGrUM  0.13.2
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  size_t last_dot = import_name.find_last_of('.');
539  std::string import_package = import_name;
540 
541  std::replace(import_name.begin(), import_name.end(), '.', '/');
542  import_name += ".o3prm";
543 
544  if (m_verbose) {
545  m_log << import_name << "' ... " << std::endl << std::flush;
546  }
547 
548  std::ifstream file_test;
549  bool found = false;
550  std::string import_abs_filename;
551 
552  // Search in o3prmr file dir.
553  std::string o3prmrFilename = context->filename();
554 
555  if (!o3prmrFilename.empty()) {
556  size_t index = o3prmrFilename.find_last_of('/');
557 
558  if (index != std::string::npos) {
559  std::string dir = o3prmrFilename.substr(0, index + 1);
560  import_abs_filename = dir + import_name;
561 
562  if (m_verbose) {
563  m_log << "# Search from filedir '" << import_abs_filename
564  << "' ... " << std::flush;
565  }
566 
567  file_test.open(import_abs_filename.c_str());
568 
569  if (file_test.is_open()) {
570  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
571 
572  file_test.close();
573  found = true;
574  } else if (m_verbose) {
575  m_log << "not found." << std::endl << std::flush;
576  }
577  }
578  }
579 
580  // Deduce root path from package name.
581  std::string package = context->package();
582 
583  if (!found && !package.empty()) {
584  std::string root;
585 
586  // if filename is not empty, start from it.
587  std::string filename = context->filename();
588 
589  if (!filename.empty()) {
590  size_t size = filename.find_last_of('/');
591 
592  if (size != std::string::npos) {
593  root += filename.substr(0, size + 1); // take with the '/'
594  }
595  }
596 
597  //
598  root += "../";
599  int count = (int)std::count(package.begin(), package.end(), '.');
600 
601  for (int i = 0; i < count; i++)
602  root += "../";
603 
604  import_abs_filename = Directory(root).absolutePath() + import_name;
605 
606  if (m_verbose) {
607  m_log << "# Search from package '" << package << "' => '"
608  << import_abs_filename << "' ... " << std::flush;
609  }
610 
611  file_test.open(import_abs_filename.c_str());
612 
613  if (file_test.is_open()) {
614  if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
615 
616  file_test.close();
617  found = true;
618  } else if (m_verbose) {
619  m_log << "not found." << std::endl << std::flush;
620  }
621  }
622 
623  // Search import in all paths.
624  for (const auto& path : m_paths) {
625  import_abs_filename = path + import_name;
626 
627  if (m_verbose) {
628  m_log << "# Search from classpath '" << import_abs_filename
629  << "' ... " << std::flush;
630  }
631 
632  file_test.open(import_abs_filename.c_str());
633 
634  if (file_test.is_open()) {
635  if (m_verbose) { m_log << " found !" << std::endl << std::flush; }
636 
637  file_test.close();
638  found = true;
639  break;
640  } else if (m_verbose) {
641  m_log << " not found." << std::endl << std::flush;
642  }
643  }
644 
645  if (!found) {
646  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
647 
648  addError("import not found.");
649  return false;
650  }
651 
652  // May throw std::IOError if file does't exist
653  Size previousO3prmError = m_reader->errors();
654  Size previousO3prmrError = errors();
655 
656  try {
657  m_reader->readFile(import_abs_filename, import_package);
658 
659  // Show errors and warning
660  if (m_verbose
661  && (m_reader->errors() > (unsigned int)previousO3prmError
662  || errors() > previousO3prmrError)) {
663  m_log << "Finished with errors." << std::endl;
664  } else if (m_verbose) {
665  m_log << "Finished." << std::endl;
666  }
667 
668  } catch (const IOError& err) {
669  if (m_verbose) { m_log << "Finished with errors." << std::endl; }
670 
671  addError(err.errorContent());
672  }
673 
674  // Add o3prm errors and warnings to o3prmr errors
675  for (; previousO3prmError < m_reader->errorsContainer().count();
676  previousO3prmError++) {
677  m_errors.add(m_reader->errorsContainer().error(previousO3prmError));
678  }
679 
680  return errors() == previousO3prmrError;
681 
682  } catch (const Exception& err) {
683  if (m_verbose) { m_log << "Finished with exceptions." << std::endl; }
684 
685  addError(err.errorContent());
686  return false;
687  }
688  }
689 
690  std::string O3prmrInterpreter::findSystemName(std::string& s) {
691  size_t dot = s.find_first_of('.');
692  std::string name = s.substr(0, dot);
693 
694  // We look first for real system, next for alias.
695  if (prm()->isSystem(name)) {
696  s = s.substr(dot + 1);
697  return name;
698  }
699 
700  if (!m_context->aliasToImport(name).empty()) {
701  s = s.substr(dot + 1);
702  return m_context->aliasToImport(name);
703  }
704 
705  while (dot != std::string::npos) {
706  if (prm()->isSystem(name)) {
707  s = s.substr(dot + 1);
708  return name;
709  }
710 
711  dot = s.find('.', dot + 1);
712  name = s.substr(0, dot);
713  }
714 
715  throw "could not find any system in '" + s + "'.";
716  }
717 
718  std::string
720  const PRMSystem< double >& sys) {
721  // We have found system before, so 's' has been stripped.
722  size_t dot = s.find_first_of('.');
723  std::string name = s.substr(0, dot);
724 
725  if (!sys.exists(name))
726  throw "'" + name + "' is not an instance of system '" + sys.name()
727  + "'.";
728 
729  s = s.substr(dot + 1);
730  return name;
731  }
732 
734  const std::string& s, const PRMInstance< double >& instance) {
735  if (!instance.exists(s))
736  throw "'" + s + "' is not an attribute of instance '" + instance.name()
737  + "'.";
738 
739  return s;
740  }
741 
742  // After this method, ident doesn't contains the system name anymore.
743  const PRMSystem< double >& O3prmrInterpreter::system(std::string& ident) {
744  try {
745  return prm()->getSystem(findSystemName(ident));
746  } catch (const std::string&) {}
747 
748  if ((m_context->mainImport() != 0)
750  return prm()->getSystem(m_context->mainImport()->value);
751 
752  throw "could not find any system or alias in '" + ident
753  + "' and no default alias has been set.";
754  }
755 
757 
758  bool
760  const typename PRMInference< double >::Chain& chain = command->chain;
761 
762  // Generate the inference engine if it doesn't exist.
763  if (!m_inf) { generateInfEngine(*(command->system)); }
764 
765  // Prevent from something
766  if (m_inf->hasEvidence(chain))
767  addWarning(command->leftValue + " is already observed");
768 
769  m_inf->addEvidence(chain, command->potentiel);
770 
771  if (m_verbose)
772  m_log << "# Added evidence " << command->rightValue << " over attribute "
773  << command->leftValue << std::endl;
774 
775  return true;
776 
777  } catch (OperationNotAllowed& ex) {
778  addError("something went wrong when adding evidence " + command->rightValue
779  + " over " + command->leftValue + " : " + ex.errorContent());
780  return false;
781 
782  } catch (const std::string& msg) {
783  addError(msg);
784  return false;
785  }
786 
788 
790  const UnobserveCommand< double >* command) try {
791  std::string name = command->value;
792  typename PRMInference< double >::Chain chain = command->chain;
793 
794  // Prevent from something
795  if (!m_inf || !m_inf->hasEvidence(chain)) {
796  addWarning(name + " was not observed");
797  } else {
798  m_inf->removeEvidence(chain);
799 
800  if (m_verbose)
801  m_log << "# Removed evidence over attribute " << name << std::endl;
802  }
803 
804  return true;
805 
806  } catch (const std::string& msg) {
807  addError(msg);
808  return false;
809  }
810 
813  const std::string& query = command->value;
814 
815  if (m_inf_map.exists(command->system)) {
816  m_inf = m_inf_map[command->system];
817  } else {
818  m_inf = nullptr;
819  }
820 
821  // Create inference engine if it has not been already created.
822  if (!m_inf) { generateInfEngine(*(command->system)); }
823 
824  // Inference
825  if (m_verbose) {
826  m_log << "# Starting inference over query: " << query << "... "
827  << std::endl;
828  }
829 
830  Timer timer;
831  timer.reset();
832 
834  m_inf->marginal(command->chain, m);
835 
836  // Compute spent time
837  double t = timer.step();
838 
839  if (m_verbose) { m_log << "Finished." << std::endl; }
840 
841  if (m_verbose) {
842  m_log << "# Time in seconds (accuracy ~0.001): " << t << std::endl;
843  }
844 
845  // Show results
846 
847  if (m_verbose) { m_log << std::endl; }
848 
849  QueryResult result;
850  result.command = query;
851  result.time = t;
852 
853  Instantiation j(m);
854  const PRMAttribute< double >& attr = *(command->chain.second);
855 
856  for (j.setFirst(); !j.end(); j.inc()) {
857  // auto label_value = j.val ( attr.type().variable() );
858  auto label_value = j.val(0);
859  std::string label = attr.type().variable().label(label_value);
860  float value = float(m.get(j));
861 
862  SingleResult singleResult;
863  singleResult.label = label;
864  singleResult.p = value;
865 
866  result.values.push_back(singleResult);
867 
868  if (m_verbose) { m_log << label << " : " << value << std::endl; }
869  }
870 
871  m_results.push_back(result);
872 
873  if (m_verbose) { m_log << std::endl; }
874 
875  } catch (Exception& e) {
876  GUM_SHOWERROR(e);
877  throw "something went wrong while infering: " + e.errorContent();
878 
879  } catch (const std::string& msg) { addError(msg); }
880 
883  m_engine = command->value;
884  }
885 
888  m_bn_engine = command->value;
889  }
890 
893  if (m_verbose)
894  m_log << "# Building the inference engine... " << std::flush;
895 
896  //
897  if (m_engine == "SVED") {
898  m_inf = new SVED< double >(*(prm()), sys);
899 
900  //
901  } else if (m_engine == "SVE") {
902  m_inf = new SVE< double >(*(prm()), sys);
903 
904  } else {
905  if (m_engine != "GRD") {
906  addWarning("unkown engine '" + m_engine + "', use GRD insteed.");
907  }
908 
909  MarginalTargetedInference< double >* bn_inf = nullptr;
910  if (m_bn) { delete m_bn; }
911  m_bn = new BayesNet< double >();
912  BayesNetFactory< double > bn_factory(m_bn);
913 
914  if (m_verbose) m_log << "(Grounding the network... " << std::flush;
915 
916  sys.groundedBN(bn_factory);
917 
918  if (m_verbose) m_log << "Finished)" << std::flush;
919 
920  // bn_inf = new LazyPropagation<double>( *m_bn );
921  bn_inf = new VariableElimination< double >(m_bn);
922 
923  auto grd_inf = new GroundedInference< double >(*(prm()), sys);
924  grd_inf->setBNInference(bn_inf);
925  m_inf = grd_inf;
926  }
927 
928  m_inf_map.insert(&sys, m_inf);
929  if (m_verbose) m_log << "Finished." << std::endl;
930  }
931 
932  /* **************************************************************************
933  */
934 
937 
940 
943 
946  if (i >= count()) throw "Index out of bound.";
947 
948  return m_errors.error(i);
949  }
950 
953  return m_errors;
954  }
955 
957  void O3prmrInterpreter::showElegantErrors(std::ostream& o) const {
959  }
960 
964  }
965 
967  void O3prmrInterpreter::showErrorCounts(std::ostream& o) const {
969  }
970 
971  /* **************************************************************************
972  */
973 
975  void O3prmrInterpreter::addError(std::string msg) {
977 
978  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
979  }
980 
982  void O3prmrInterpreter::addWarning(std::string msg) {
984 
985  if (m_verbose) m_log << m_errors.last().toString() << std::endl;
986  }
987 
988  } // namespace o3prmr
989  } // namespace prm
990 } // namespace gum
ParseError last() const
Returns the last added error.
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)
unsigned long Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:50
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
void elegantErrorsAndWarnings(std::ostream &o) const
Print errors on output stream.
Potential< GUM_SCALAR > potentiel
bool isSystem(const std::string &name) const
Definition: PRM_tpl.h:86
void addSession(const O3prmrSession< GUM_SCALAR > &session)
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.
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 gum::prm::PRMInference< double > * inference() const
Retrieve inference motor object.
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.
bool isInSyntaxMode() const
syntax mode don&#39;t process anything, just check syntax. Default is false.
#define GUM_SHOWERROR(e)
Definition: exceptions.h:73
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.
bool exists(const std::string &name) const
Retruns true either if name is an instance or an array in this PRMSystem.
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...
<agrum/BN/inference/variableElimination.h>
DiscreteVariable & variable()
Return a reference on the DiscreteVariable contained in this.
Definition: PRMType_tpl.h:135
Class representing Bayesian networks.
void add(ParseError error)
Add an error object to the container.
This class is used contain and manipulate gum::ParseError.
const ImportCommand * mainImport() const
bool checkSetGndEngine(SetGndEngineCommand *command)
<agrum/BN/inference/marginalTargetedInference.h>
gum is the global namespace for all aGrUM entities
Definition: agrum.h:25
bool hasEvidence(const PRMInstance< GUM_SCALAR > &i) const
Returns true if i has evidence.
bool checkQuery(QueryCommand< double > *command)
void showElegantErrorsAndWarnings(std::ostream &o=std::cerr) const
send on std::cerr the list of errors or warnings
Implementation of a variable elimination algorithm for inference in Bayesian Networks.
std::string aliasToImport(const std::string &alias)
bool checkUnobserve(UnobserveCommand< double > *command)
const std::string & name() const
Returns the name of this object.
Definition: PRMObject_inl.h:32
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
std::string findSystemName(std::string &s)
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
double step() const
Returns the delta time between now and the last reset() call (or the constructor).
Definition: timer_inl.h:39
void reset()
Reset the timer.
Definition: timer_inl.h:29
Headers of SVED (Structured Value Elimination with d-seperation).
const ErrorsContainer & errorsContainer() const
publishing Errors API
const PRMSystem< GUM_SCALAR > * system
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it&#39;s NodeId in the relational skeleton.
Size errors() const
publishing Errors API
ParseError error(Idx i) const
throw a string error if i >= count
void inc()
Operator increment.
void showElegantErrors(std::ostream &o=std::cerr) const
send on std::cerr the list of errors
std::string toString() const
Return a std::string representation of this gum::ParseError.
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.
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
Definition: SVED.h:60
Size count() const
En cas d&#39;échec, l&#39;API de gestion d&#39;erreurs est présente.
void elegantErrors(std::ostream &o) const
Print errors on output stream.
std::vector< SingleResult > values
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:145
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)
ErrorsContainer errorsContainer() const
Return container with all errors.
gum::prm::PRMInference< double > * m_inf
virtual PRMType< GUM_SCALAR > & type()=0
See gum::PRMClassElement::type().
bool end() const
Returns true if the Instantiation reached the end.
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 ...
std::string absolutePath() const
Returns directory absolute path.
Definition: utils_dir.cpp:88
const std::string errorContent() const
Returns the message content.
Definition: exceptions.h:132
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
bool interpretFile(const std::string &filename)
Interpret the file or the command line.
Represent a o3prmr context, with an import, and some sequencials commands.
bool checkObserve(ObserveCommand< double > *command)
bool exists(NodeId id) const
Returns true if id matches an PRMAttribute<GUM_SCALAR> in this PRMInstance<GUM_SCALAR>.
void syntheticResults(std::ostream &o) const
Print errors on output stream.
ParseError error(Idx i) const
Returns the i-th error.
Size count() const
Returns the number of errors and warnings.
void showErrorCounts(std::ostream &o=std::cerr) const
send on std::cerr the number of errors and the number of warnings
Headers of O3prmInterpreter.
void setGndEngine(const SetGndEngineCommand *command)
void setFirst()
Assign the first values to the tuple of the Instantiation.
std::vector< ImportCommand * > imports() const
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
void groundedBN(BayesNetFactory< GUM_SCALAR > &factory) const
Returns the grounded Bayesian Network of this system.
Definition: PRMSystem_tpl.h:81
bool isVerboseMode() const
verbose mode show more details on the program execution. Default is false.
Class used to compute response times for benchmark purposesThis class represents a classic timer...
Definition: timer.h:48
~O3prmrInterpreter()
Destructor. Delete current context.
bool unobserve(const UnobserveCommand< double > *command)
Implementation of a Shafer-Shenoy&#39;s-like version of lazy propagation for inference in Bayesian Networ...
O3prmrContext< double > * getContext() const
Getter and setter for the context.
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...
std::vector< O3prmrSession< GUM_SCALAR > * > sessions() const
void removeEvidence(const Chain &chain)
Remove evidence on the given instance&#39;s elt.
unsigned long Idx
Type for indexes.
Definition: types.h:43
PRMInference< GUM_SCALAR >::Chain chain
std::string __readFile(const std::string &file)
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)
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setContext(O3prmrContext< double > *context)
Setter for the context.
#define GUM_ERROR(type, msg)
Definition: exceptions.h:66
<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.
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