59#include <agrum/PRM/o3prmr/cocoR/Parser.h>
109 if (path.length() && path.back() !=
'/') { path = path +
'/'; }
111 std::filesystem::directory_entry dir(path);
157 std::string file_content =
_readFile_(filename);
164 unsigned char* buffer =
new unsigned char[file_content.length() + 1];
165 strcpy((
char*)buffer, file_content.c_str());
166 Scanner s(buffer,
int(file_content.length() + 1));
168 p.setO3prmrContext(&c);
173 if (
errors() > 0) {
return false; }
180 for (
size_t i = 0; i <
m_paths.size(); i++) {
197 std::ifstream istream(file, std::ifstream::binary);
200 istream.seekg(0, istream.end);
201 int length = int(istream.tellg());
202 istream.seekg(0, istream.beg);
205 str.resize(length,
' ');
206 char* begin = &*str.begin();
208 istream.read(begin, length);
221 Scanner s((
unsigned char*)line.c_str(), (
int)line.length());
223 p.setO3prmrContext(&c);
227 if (
errors() > 0)
return false;
246 if (
errors() > 0)
return false;
249 std::vector< O3prmrSession< double >* > sessions = c->
sessions();
251 for (
const auto session: sessions)
252 for (
auto command: session->commands()) {
257 switch (command->type()) {
281 }
catch (std::string& err) {
289 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
315 if (
errors() > 0)
return false;
318 for (
const auto command: context->
imports()) {
321 bool succeed =
import(context, command->value);
326 if (succeed)
m_context->addImport(*command);
330 m_log <<
"## Check semantic for " << context->
sessions().size() <<
" sessions"
334 for (
const auto session: context->
sessions()) {
335 std::string sessionName = session->name();
339 m_log <<
"## Start session '" << sessionName <<
"'..." << std::endl << std::endl;
341 for (
const auto command: session->commands()) {
343 m_log <<
"# * Going to check command : " << command->toString() << std::endl;
352 switch (command->type()) {
375 +
"\n -> Command not processed.");
381 }
catch (std::string& err) {
389 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
400 if (sessionName ==
"default" &&
m_context->sessions().size() > 0)
401 *(
m_context->sessions().back()) += *new_session;
402 else m_context->addSession(*new_session);
406 <<
"## Session '" << sessionName <<
"' finished." << std::endl
431 std::string left_val = command->
leftValue;
432 const std::string right_val = command->
rightValue;
441 command->
chain = std::make_pair(&instance, &attr);
445 command->
potentiel.add(chain.second->type().variable());
450 if (chain.second->type().variable().label(i.
val(chain.second->type().variable()))
459 if (!found)
addError(right_val +
" is not a label of " + left_val);
474 std::string name = command->
value;
484 command->
chain = std::make_pair(&instance, &attr);
497 std::string name = command->
value;
507 command->
chain = std::make_pair(&instance, &attr);
523 if (
m_verbose) {
m_log <<
"# Loading system '" << import_name <<
"' => '" << std::flush; }
525 std::string import_package = import_name;
527 std::replace(import_name.begin(), import_name.end(),
'.',
'/');
528 import_name +=
".o3prm";
530 if (
m_verbose) {
m_log << import_name <<
"' ... " << std::endl << std::flush; }
532 std::ifstream file_test;
534 std::string import_abs_filename;
537 std::string o3prmrFilename = context->
filename();
539 if (!o3prmrFilename.empty()) {
540 size_t index = o3prmrFilename.find_last_of(
'/');
542 if (index != std::string::npos) {
543 std::string dir = o3prmrFilename.substr(0, index + 1);
544 import_abs_filename = dir + import_name;
547 m_log <<
"# Search from filedir '" << import_abs_filename <<
"' ... " << std::flush;
550 file_test.open(import_abs_filename.c_str());
552 if (file_test.is_open()) {
558 m_log <<
"not found." << std::endl << std::flush;
564 std::string
package = context->package();
566 if (!found && !package.empty()) {
570 std::string filename = context->filename();
572 if (!filename.empty()) {
573 size_t size = filename.find_last_of(
'/');
575 if (size != std::string::npos) {
576 root += filename.substr(0, size + 1);
582 int count = (
int)std::count(package.begin(), package.end(),
'.');
584 for (
int i = 0; i <
count; i++)
587 import_abs_filename = std::filesystem::absolute(std::filesystem::path(root)
588 / std::filesystem::path(import_name))
592 m_log <<
"# Search from package '" <<
package << "' => '" << import_abs_filename
593 << "' ... " << std::flush;
596 file_test.open(import_abs_filename.c_str());
598 if (file_test.is_open()) {
604 m_log <<
"not found." << std::endl << std::flush;
609 for (
const auto& path:
m_paths) {
610 import_abs_filename = path + import_name;
613 m_log <<
"# Search from classpath '" << import_abs_filename <<
"' ... " << std::flush;
616 file_test.open(import_abs_filename.c_str());
618 if (file_test.is_open()) {
619 if (
m_verbose) {
m_log <<
" found !" << std::endl << std::flush; }
625 m_log <<
" not found." << std::endl << std::flush;
641 m_reader->readFile(import_abs_filename, import_package);
645 && (
m_reader->errors() > (
unsigned int)previousO3prmError
646 ||
errors() > previousO3prmrError)) {
647 m_log <<
"Finished with errors." << std::endl;
649 m_log <<
"Finished." << std::endl;
659 for (; previousO3prmError <
m_reader->errorsContainer().
count(); previousO3prmError++) {
663 return errors() == previousO3prmrError;
666 if (
m_verbose) {
m_log <<
"Finished with exceptions." << std::endl; }
674 size_t dot = s.find_first_of(
'.');
675 std::string name = s.substr(0, dot);
678 if (
prm()->isSystem(name)) {
679 s = s.substr(dot + 1);
683 if (!
m_context->aliasToImport(name).empty()) {
684 s = s.substr(dot + 1);
688 while (dot != std::string::npos) {
689 if (
prm()->isSystem(name)) {
690 s = s.substr(dot + 1);
694 dot = s.find(
'.', dot + 1);
695 name = s.substr(0, dot);
698 throw "could not find any system in '" + s +
"'.";
704 size_t dot = s.find_first_of(
'.');
705 std::string name = s.substr(0, dot);
708 throw "'" + name +
"' is not an instance of system '" + sys.
name() +
"'.";
710 s = s.substr(dot + 1);
717 throw "'" + s +
"' is not an attribute of instance '" + instance.
name() +
"'.";
726 }
catch (
const std::string&) {}
731 throw "could not find any system or alias in '" + ident
732 +
"' and no default alias has been set.";
749 m_log <<
"# Added evidence " << command->
rightValue <<
" over attribute "
755 addError(
"something went wrong when adding evidence " + command->rightValue +
" over "
759 }
catch (
const std::string& msg) {
767 std::string name = command->
value;
774 m_inf->removeEvidence(chain);
776 if (
m_verbose)
m_log <<
"# Removed evidence over attribute " << name << std::endl;
781 }
catch (
const std::string& msg) {
801 m_log <<
"# Starting inference over query: " <<
query <<
"... " << std::endl;
811 double t = timer.
step();
815 if (
m_verbose) {
m_log <<
"# Time in seconds (accuracy ~0.001): " << t << std::endl; }
830 auto label_value = j.
val(0);
832 float value = float(m.
get(j));
835 singleResult.
label = label;
836 singleResult.
p = value;
838 result.
values.push_back(singleResult);
849 throw "something went wrong while infering: " + e.
errorContent();
851 }
catch (
const std::string& msg) {
addError(msg); }
865 if (
m_verbose)
m_log <<
"# Building the inference engine... " << std::flush;
885 if (
m_verbose)
m_log <<
"(Grounding the network... " << std::flush;
895 grd_inf->setBNInference(bn_inf);
917 if (i >=
count())
throw "Index out of bound.";
932 m_errors.elegantErrorsAndWarnings(o);
This file contains abstract class definitions for Bayesian networks inference classes.
Class representing Bayesian networks.
Headers of O3prmInterpreter.
Headers of SVED (Structured Value Elimination with d-seperation).
Headers of SVE (Structured Variable Elimination).
A factory class to ease BayesNet construction.
virtual std::string label(Idx i) const =0
get the indice-th label. This method is pure virtual.
This class is used contain and manipulate gum::ParseError.
Base class for all aGrUM's exceptions.
GUM_NODISCARD std::string errorContent() const
Returns the message content.
Exception : input/output problem.
Class for assigning/browsing values to tuples of discrete variables.
bool end() const
Returns true if the Instantiation reached the end.
void inc()
Operator increment.
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFirst()
Assign the first values to the tuple of the Instantiation.
<agrum/BN/inference/marginalTargetedInference.h>
virtual GUM_SCALAR get(const Instantiation &i) const final
Default implementation of MultiDimContainer::get().
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
This class is used to represent parsing errors for the different parser implemented in aGrUM.
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Class used to compute response times for benchmark purposes.
void reset()
Reset the timer.
double step() const
Returns the delta time between now and the last reset() call (or the constructor).
Implementation of a Variable Elimination's-like version of lazy propagation for inference in Bayesian...
<agrum/PRM/groundedInference.h>
virtual PRMType & type()=0
See gum::PRMClassElement::type().
std::pair< const PRMInstance< GUM_SCALAR > *, const PRMAttribute< GUM_SCALAR > * > Chain
Code alias.
bool exists(NodeId id) const
Returns true if id matches an PRMAttribute<GUM_SCALAR> in this PRMInstance<GUM_SCALAR>.
PRMAttribute< GUM_SCALAR > & get(NodeId id)
Getter on an PRMAttribute<GUM_SCALAR> of this PRMInstance<GUM_SCALAR>.
const std::string & name() const
Returns the name of this object.
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it's NodeId in the relational skeleton.
bool exists(const std::string &name) const
Retruns true either if name is an instance or an array in this PRMSystem.
void groundedBN(BayesNetFactory< GUM_SCALAR > &factory) const
Returns the grounded Bayesian network of this system.
DiscreteVariable & variable()
Return a reference on the DiscreteVariable contained in this.
PRMSystem< GUM_SCALAR > & getSystem(const std::string &name)
Returns a constant reference on a PRMSystem<GUM_SCALAR> given it's name.
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
This class is an implementation of the Structured Variable Elimination algorithm on PRM<GUM_SCALAR>.
This is an abstract class.
Represent a o3prmr context, with an import, and some sequencials commands.
std::vector< O3prmrSession< GUM_SCALAR > * > sessions() const
std::vector< ImportCommand * > imports() const
std::string filename() const
~O3prmrInterpreter()
Destructor. Delete current context.
const PRMSystem< double > & system(std::string &ident)
std::string _readFile_(const std::string &file)
bool import(O3prmrContext< double > *context, std::string import)
bool checkQuery(QueryCommand< double > *command)
std::string findAttributeName(const std::string &s, const gum::prm::PRMInstance< double > &instance)
void addPath(std::string path)
Root paths to search from there packages. Default are './' and one is calculate from request package ...
void showElegantErrors(std::ostream &o=std::cerr) const
send on std::cerr the list of errors
bool observe(const ObserveCommand< double > *command)
bool checkSetGndEngine(SetGndEngineCommand *command)
void showElegantErrorsAndWarnings(std::ostream &o=std::cerr) const
send on std::cerr the list of errors or warnings
bool interpretFile(const std::string &filename)
Interpret the file or the command line.
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...
void setContext(O3prmrContext< double > *context)
Setter for the context.
ErrorsContainer errorsContainer() const
Return container with all errors.
void showErrorCounts(std::ostream &o=std::cerr) const
send on std::cerr the number of errors and the number of warnings
void setSyntaxMode(bool f)
syntax mode don't process anything, just check syntax.
const gum::prm::PRMInference< double > * inference() const
Retrieve inference motor object.
O3prmrInterpreter()
This constructor create an empty context.
bool checkObserve(ObserveCommand< double > *command)
std::vector< QueryResult > m_results
gum::prm::PRMInference< double > * m_inf
bool isInSyntaxMode() const
syntax mode don't process anything, just check syntax. Default is false.
O3prmrContext< double > * getContext() const
Getter and setter for the context.
HashTable< const PRMSystem< double > *, PRMInference< double > * > m_inf_map
gum::BayesNet< double > * m_bn
void generateInfEngine(const gum::prm::PRMSystem< double > &sys)
void clearPaths()
Root paths to search from there packages. Default are './' and one is calculate from request package ...
bool checkUnobserve(UnobserveCommand< double > *command)
O3prmrContext< double > * m_context
const std::vector< QueryResult > & results() const
Return a vector of QueryResults. Each QueryResults is a struct with query command,...
std::vector< std::string > m_paths
void addError(std::string msg)
gum::prm::o3prm::O3prmReader< double > * m_reader
bool isVerboseMode() const
verbose mode show more details on the program execution. Default is false.
bool checkSemantic(O3prmrContext< double > *context)
Check semantic validity of context.
bool interpret(O3prmrContext< double > *c)
Crée le prm correspondant au contexte courant.
void setGndEngine(const SetGndEngineCommand *command)
void setEngine(const SetEngineCommand *command)
std::string findInstanceName(std::string &s, const gum::prm::PRMSystem< double > &sys)
const gum::prm::PRM< double > * prm() const
Retrieve prm object.
bool checkSetEngine(SetEngineCommand *command)
std::string findSystemName(std::string &s)
void query(const QueryCommand< double > *command)
bool interpretLine(const std::string &line)
bool unobserve(const UnobserveCommand< double > *command)
ParseError error(Idx i) const
throw a string error if i >= count
gum::ErrorsContainer m_errors
Size count() const
En cas d'échec, l'API de gestion d'erreurs est présente.
void addWarning(std::string msg)
void setVerboseMode(bool f)
verbose mode show more details on the program execution.
void addCommand(const O3prmrCommand *command)
PRMInference< GUM_SCALAR >::Chain chain
const PRMSystem< GUM_SCALAR > * system
Tensor< GUM_SCALAR > potentiel
const PRMSystem< GUM_SCALAR > * system
PRMInference< GUM_SCALAR >::Chain chain
std::vector< SingleResult > values
std::string toString() const
PRMInference< GUM_SCALAR >::Chain chain
const PRMSystem< GUM_SCALAR > * system
#define GUM_ERROR(type, msg)
Headers of GroundedInference.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size Idx
Type for indexes.
Implementation of a Shafer-Shenoy's-like version of lazy propagation for inference in Bayesian networ...
namespace for all probabilistic relational models entities
gum is the global namespace for all aGrUM entities
Implementation of a variable elimination algorithm for inference in Bayesian networks.