62#pragma push_macro("GUM_COCOR_PUBLIC")
63#undef GUM_COCOR_PUBLIC
64#define GUM_COCOR_PUBLIC GUM_PUBLIC_PRM
65#include <agrum/PRM/o3prmr/cocoR/Parser.h>
66#pragma pop_macro("GUM_COCOR_PUBLIC")
113 if (path.length() && path.back() !=
'/') { path = path +
'/'; }
115 std::filesystem::directory_entry dir(path);
161 std::string file_content =
_readFile_(filename);
168 unsigned char* buffer =
new unsigned char[file_content.length() + 1];
169 strcpy((
char*)buffer, file_content.c_str());
170 Scanner s(buffer,
int(file_content.length() + 1));
172 p.setO3prmrContext(&c);
177 if (
errors() > 0) {
return false; }
184 for (
size_t i = 0; i <
m_paths.size(); i++) {
201 std::ifstream istream(std::string(file), std::ifstream::binary);
204 istream.seekg(0, istream.end);
205 int length = int(istream.tellg());
206 istream.seekg(0, istream.beg);
209 str.resize(length,
' ');
210 char* begin = &*str.begin();
212 istream.read(begin, length);
225 Scanner s((
unsigned char*)line.data(), (
int)line.length());
227 p.setO3prmrContext(&c);
231 if (
errors() > 0)
return false;
250 if (
errors() > 0)
return false;
253 std::vector< O3prmrSession< double >* > sessions = c->
sessions();
255 for (
const auto session: sessions)
256 for (
auto command: session->commands()) {
261 switch (command->type()) {
285 }
catch (std::string& err) {
293 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
319 if (
errors() > 0)
return false;
322 for (
const auto command: context->
imports()) {
325 bool succeed =
import(context, command->value);
334 m_log <<
"## Check semantic for " << context->
sessions().size() <<
" sessions"
338 for (
const auto session: context->
sessions()) {
339 std::string sessionName = session->name();
343 m_log <<
"## Start session '" << sessionName <<
"'..." << std::endl << std::endl;
345 for (
const auto command: session->commands()) {
347 m_log <<
"# * Going to check command : " << command->toString() << std::endl;
356 switch (command->type()) {
379 +
"\n -> Command not processed.");
385 }
catch (std::string& err) {
393 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
410 <<
"## Session '" << sessionName <<
"' finished." << std::endl
435 std::string left_val = command->
leftValue;
436 const std::string right_val = command->
rightValue;
445 command->
chain = std::make_pair(&instance, &attr);
449 command->
potentiel.add(chain.second->type().variable());
454 if (chain.second->type().variable().label(i.
val(chain.second->type().variable()))
463 if (!found)
addError(right_val +
" is not a label of " + left_val);
477 std::string name = command->
value;
487 command->
chain = std::make_pair(&instance, &attr);
499 std::string name = command->
value;
509 command->
chain = std::make_pair(&instance, &attr);
524 if (
m_verbose) {
m_log <<
"# Loading system '" << import_name <<
"' => '" << std::flush; }
526 std::string import_package = import_name;
528 std::replace(import_name.begin(), import_name.end(),
'.',
'/');
529 import_name +=
".o3prm";
531 if (
m_verbose) {
m_log << import_name <<
"' ... " << std::endl << std::flush; }
533 std::ifstream file_test;
535 std::string import_abs_filename;
538 std::string o3prmrFilename = context->
filename();
540 if (!o3prmrFilename.empty()) {
541 if (
auto index = o3prmrFilename.find_last_of(
'/'); index != std::string::npos) {
542 std::string dir = o3prmrFilename.substr(0, index + 1);
543 import_abs_filename = dir + import_name;
546 m_log <<
"# Search from filedir '" << import_abs_filename <<
"' ... " << std::flush;
549 file_test.open(import_abs_filename.c_str());
551 if (file_test.is_open()) {
557 m_log <<
"not found." << std::endl << std::flush;
563 std::string
package = context->package();
565 if (!found && !package.empty()) {
569 std::string filename = context->filename();
571 if (!filename.empty()) {
572 if (auto size = filename.find_last_of(
'/'); size != std::string::npos) {
573 root += filename.substr(0, size + 1);
579 int count = (
int)std::count(package.begin(), package.end(),
'.');
581 for (
int i = 0; i <
count; i++)
584 import_abs_filename = std::filesystem::absolute(std::filesystem::path(root)
585 / std::filesystem::path(import_name))
589 m_log <<
"# Search from package '" <<
package << "' => '" << import_abs_filename
590 << "' ... " << std::flush;
593 file_test.open(import_abs_filename.c_str());
595 if (file_test.is_open()) {
601 m_log <<
"not found." << std::endl << std::flush;
606 for (
const auto& path:
m_paths) {
607 import_abs_filename = path + import_name;
610 m_log <<
"# Search from classpath '" << import_abs_filename <<
"' ... " << std::flush;
613 file_test.open(import_abs_filename.c_str());
615 if (file_test.is_open()) {
616 if (
m_verbose) {
m_log <<
" found !" << std::endl << std::flush; }
622 m_log <<
" not found." << std::endl << std::flush;
638 m_reader->readFile(import_abs_filename, import_package);
642 && (
m_reader->errors() > (
unsigned int)previousO3prmError
643 ||
errors() > previousO3prmrError)) {
644 m_log <<
"Finished with errors." << std::endl;
646 m_log <<
"Finished." << std::endl;
655 for (; previousO3prmError <
m_reader->errorsContainer().
count(); previousO3prmError++) {
659 return errors() == previousO3prmrError;
661 if (
m_verbose) {
m_log <<
"Finished with exceptions." << std::endl; }
669 size_t dot = s.find_first_of(
'.');
670 std::string name = s.substr(0, dot);
673 if (
prm()->isSystem(name)) {
674 s = s.substr(dot + 1);
679 s = s.substr(dot + 1);
683 while (dot != std::string::npos) {
684 if (
prm()->isSystem(name)) {
685 s = s.substr(dot + 1);
689 dot = s.find(
'.', dot + 1);
690 name = s.substr(0, dot);
693 throw "could not find any system in '" + s +
"'.";
699 size_t dot = s.find_first_of(
'.');
700 std::string name = s.substr(0, dot);
703 throw "'" + name +
"' is not an instance of system '" + sys.
name() +
"'.";
705 s = s.substr(dot + 1);
712 throw "'" + std::string{s} +
"' is not an attribute of instance '" + instance.
name()
715 return std::string{s};
722 }
catch (
const std::string&) {}
727 throw "could not find any system or alias in '" + ident
728 +
"' and no default alias has been set.";
745 m_log <<
"# Added evidence " << command->
rightValue <<
" over attribute "
750 addError(
"something went wrong when adding evidence " + command->rightValue +
" over "
753 }
catch (
const std::string& msg) {
761 std::string name = command->
value;
770 if (
m_verbose)
m_log <<
"# Removed evidence over attribute " << name << std::endl;
774 }
catch (
const std::string& msg) {
794 m_log <<
"# Starting inference over query: " <<
query <<
"... " << std::endl;
804 double t = timer.
step();
808 if (
m_verbose) {
m_log <<
"# Time in seconds (accuracy ~0.001): " << t << std::endl; }
823 auto label_value = j.
val(0);
825 float value = float(m.
get(j));
828 singleResult.
label = label;
829 singleResult.
p = value;
831 result.
values.push_back(singleResult);
841 throw "something went wrong while infering: " + e.
errorContent();
842 }
catch (
const std::string& msg) {
addError(msg); }
856 if (
m_verbose)
m_log <<
"# Building the inference engine... " << std::flush;
875 if (
m_verbose)
m_log <<
"(Grounding the network... " << std::flush;
885 grd_inf->setBNInference(bn_inf);
907 if (i >=
count())
throw "Index out of bound.";
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-separation).
Headers of SVE (Structured Variable Elimination).
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.
ParseError last() const
Returns the last added error.
Size count() const
Returns the number of errors and warnings.
ParseError error(Idx i) const
Returns the i-th error.
void addError(std::string_view msg, std::string_view filename, Idx line, Idx col)
Adds an error.
Size error_count
Number of errors detected.
void elegantErrorsAndWarnings(std::ostream &o) const
Print errors on output stream.
void addWarning(std::string_view msg, std::string_view filename, Idx line, Idx col)
Adds a warning.
void syntheticResults(std::ostream &o) const
Print errors on output stream.
void elegantErrors(std::ostream &o) const
Print errors on output stream.
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>
GUM_ELEMENT 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.
std::string toString() const
Return a std::string representation of this gum::ParseError.
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).
GroundedInference(const PRM< GUM_SCALAR > &prm, const PRMSystem< GUM_SCALAR > &system)
Default constructor.
PRMAttribute is a member of a Class in a PRM.
PRMType & type() override=0
See gum::PRMClassElement::type().
std::pair< const PRMInstance< GUM_SCALAR > *, const PRMAttribute< GUM_SCALAR > * > Chain
Code alias.
void addEvidence(const Chain &chain, const Tensor< GUM_SCALAR > &p)
Add an evidence to the given instance's elt.
void posterior(const Chain &chain, Tensor< GUM_SCALAR > &m)
Compute the posterior of the formal attribute pointed by chain and stores it in m.
bool hasEvidence(const PRMInstance< GUM_SCALAR > &i) const
Returns true if i has evidence.
void removeEvidence(const Chain &chain)
Remove evidence on the given instance's elt.
An PRMInstance is a Bayesian network fragment defined by a Class and used in a PRMSystem.
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.
bool exists(std::string_view name) const
Retruns true either if name is an instance or an array in this PRMSystem.
PRMInstance< GUM_SCALAR > & get(NodeId id)
Returns an PRMInstance given it's NodeId in the relational skeleton.
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.
This class represents a Probabilistic Relational PRMSystem<GUM_SCALAR>.
SVED(const PRM< GUM_SCALAR > &prm, const PRMSystem< GUM_SCALAR > &model)
Default Constructor.
SVE(const PRM< GUM_SCALAR > &prm, const PRMSystem< GUM_SCALAR > &system)
Default Constructor.
gum::prm::PRM< GUM_SCALAR > * prm()
void addClassPath(std::string_view class_path)
Add a list of paths to look for o3prm files.
This is an abstract class.
Represent a o3prmr context, with an import, and some sequencials commands.
void addImport(int line, std::string_view import, std::string_view alias)
std::vector< O3prmrSession< GUM_SCALAR > * > sessions() const
void addSession(const O3prmrSession< GUM_SCALAR > &session)
std::vector< ImportCommand * > imports() const
const ImportCommand * mainImport() const
std::string aliasToImport(std::string_view alias)
std::string filename() const
~O3prmrInterpreter()
Destructor. Delete current context.
const PRMSystem< double > & system(std::string &ident)
bool import(O3prmrContext< double > *context, std::string import)
bool interpretFile(std::string_view filename)
Interpret the file or the command line.
std::string _readFile_(std::string_view file)
bool checkQuery(QueryCommand< double > *command)
void addPath(std::string path)
Root paths to search from there packages. Default are './' and one is calculate from request package ...
bool interpretLine(std::string_view line)
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
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)
std::string findAttributeName(std::string_view s, const gum::prm::PRMInstance< double > &instance)
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 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.
This class contains a o3prmr session.
O3prmrSession(std::string_view name="")
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 override
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...
gum is the global namespace for all aGrUM entities
template class GUM_SHARED_PUBLIC Tensor< double >
template class GUM_PUBLIC_BN BayesNetFactory< double >
template class GUM_PUBLIC_BN BayesNet< double >
template class GUM_PUBLIC_BN VariableElimination< double >
Implementation of a variable elimination algorithm for inference in Bayesian networks.