59#include <agrum/PRM/o3prmr/cocoR/Parser.h>
106 if (path.length() && path.back() !=
'/') { path = path +
'/'; }
108 std::filesystem::directory_entry dir(path);
154 std::string file_content =
_readFile_(filename);
161 unsigned char* buffer =
new unsigned char[file_content.length() + 1];
162 strcpy((
char*)buffer, file_content.c_str());
163 Scanner s(buffer,
int(file_content.length() + 1));
165 p.setO3prmrContext(&c);
170 if (
errors() > 0) {
return false; }
177 for (
size_t i = 0; i <
m_paths.size(); i++) {
194 std::ifstream istream(std::string(file), std::ifstream::binary);
197 istream.seekg(0, istream.end);
198 int length = int(istream.tellg());
199 istream.seekg(0, istream.beg);
202 str.resize(length,
' ');
203 char* begin = &*str.begin();
205 istream.read(begin, length);
218 Scanner s((
unsigned char*)line.data(), (
int)line.length());
220 p.setO3prmrContext(&c);
224 if (
errors() > 0)
return false;
243 if (
errors() > 0)
return false;
246 std::vector< O3prmrSession< double >* > sessions = c->
sessions();
248 for (
const auto session: sessions)
249 for (
auto command: session->commands()) {
254 switch (command->type()) {
278 }
catch (std::string& err) {
286 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
312 if (
errors() > 0)
return false;
315 for (
const auto command: context->
imports()) {
318 bool succeed =
import(context, command->value);
323 if (succeed)
m_context->addImport(*command);
327 m_log <<
"## Check semantic for " << context->
sessions().size() <<
" sessions"
331 for (
const auto session: context->
sessions()) {
332 std::string sessionName = session->name();
336 m_log <<
"## Start session '" << sessionName <<
"'..." << std::endl << std::endl;
338 for (
const auto command: session->commands()) {
340 m_log <<
"# * Going to check command : " << command->toString() << std::endl;
349 switch (command->type()) {
372 +
"\n -> Command not processed.");
378 }
catch (std::string& err) {
386 if (
m_verbose)
m_log <<
"Errors : skip the rest of this session." << std::endl;
397 if (sessionName ==
"default" &&
m_context->sessions().size() > 0)
398 *(
m_context->sessions().back()) += *new_session;
399 else m_context->addSession(*new_session);
403 <<
"## Session '" << sessionName <<
"' finished." << std::endl
428 std::string left_val = command->
leftValue;
429 const std::string right_val = command->
rightValue;
438 command->
chain = std::make_pair(&instance, &attr);
442 command->
potentiel.add(chain.second->type().variable());
447 if (chain.second->type().variable().label(i.
val(chain.second->type().variable()))
456 if (!found)
addError(right_val +
" is not a label of " + left_val);
470 std::string name = command->
value;
480 command->
chain = std::make_pair(&instance, &attr);
492 std::string name = command->
value;
502 command->
chain = std::make_pair(&instance, &attr);
517 if (
m_verbose) {
m_log <<
"# Loading system '" << import_name <<
"' => '" << std::flush; }
519 std::string import_package = import_name;
521 std::replace(import_name.begin(), import_name.end(),
'.',
'/');
522 import_name +=
".o3prm";
524 if (
m_verbose) {
m_log << import_name <<
"' ... " << std::endl << std::flush; }
526 std::ifstream file_test;
528 std::string import_abs_filename;
531 std::string o3prmrFilename = context->
filename();
533 if (!o3prmrFilename.empty()) {
534 if (
auto index = o3prmrFilename.find_last_of(
'/'); index != std::string::npos) {
535 std::string dir = o3prmrFilename.substr(0, index + 1);
536 import_abs_filename = dir + import_name;
539 m_log <<
"# Search from filedir '" << import_abs_filename <<
"' ... " << std::flush;
542 file_test.open(import_abs_filename.c_str());
544 if (file_test.is_open()) {
550 m_log <<
"not found." << std::endl << std::flush;
556 std::string
package = context->package();
558 if (!found && !package.empty()) {
562 std::string filename = context->filename();
564 if (!filename.empty()) {
565 if (auto size = filename.find_last_of(
'/'); size != std::string::npos) {
566 root += filename.substr(0, size + 1);
572 int count = (
int)std::count(package.begin(), package.end(),
'.');
574 for (
int i = 0; i <
count; i++)
577 import_abs_filename = std::filesystem::absolute(std::filesystem::path(root)
578 / std::filesystem::path(import_name))
582 m_log <<
"# Search from package '" <<
package << "' => '" << import_abs_filename
583 << "' ... " << std::flush;
586 file_test.open(import_abs_filename.c_str());
588 if (file_test.is_open()) {
594 m_log <<
"not found." << std::endl << std::flush;
599 for (
const auto& path:
m_paths) {
600 import_abs_filename = path + import_name;
603 m_log <<
"# Search from classpath '" << import_abs_filename <<
"' ... " << std::flush;
606 file_test.open(import_abs_filename.c_str());
608 if (file_test.is_open()) {
609 if (
m_verbose) {
m_log <<
" found !" << std::endl << std::flush; }
615 m_log <<
" not found." << std::endl << std::flush;
631 m_reader->readFile(import_abs_filename, import_package);
635 && (
m_reader->errors() > (
unsigned int)previousO3prmError
636 ||
errors() > previousO3prmrError)) {
637 m_log <<
"Finished with errors." << std::endl;
639 m_log <<
"Finished." << std::endl;
648 for (; previousO3prmError <
m_reader->errorsContainer().
count(); previousO3prmError++) {
652 return errors() == previousO3prmrError;
654 if (
m_verbose) {
m_log <<
"Finished with exceptions." << std::endl; }
662 size_t dot = s.find_first_of(
'.');
663 std::string name = s.substr(0, dot);
666 if (
prm()->isSystem(name)) {
667 s = s.substr(dot + 1);
671 if (!
m_context->aliasToImport(name).empty()) {
672 s = s.substr(dot + 1);
676 while (dot != std::string::npos) {
677 if (
prm()->isSystem(name)) {
678 s = s.substr(dot + 1);
682 dot = s.find(
'.', dot + 1);
683 name = s.substr(0, dot);
686 throw "could not find any system in '" + s +
"'.";
692 size_t dot = s.find_first_of(
'.');
693 std::string name = s.substr(0, dot);
696 throw "'" + name +
"' is not an instance of system '" + sys.
name() +
"'.";
698 s = s.substr(dot + 1);
705 throw "'" + std::string{s} +
"' is not an attribute of instance '" + instance.
name()
708 return std::string{s};
715 }
catch (
const std::string&) {}
718 return prm()->getSystem(
m_context->mainImport()->value);
720 throw "could not find any system or alias in '" + ident
721 +
"' and no default alias has been set.";
738 m_log <<
"# Added evidence " << command->
rightValue <<
" over attribute "
743 addError(
"something went wrong when adding evidence " + command->rightValue +
" over "
746 }
catch (
const std::string& msg) {
754 std::string name = command->
value;
761 m_inf->removeEvidence(chain);
763 if (
m_verbose)
m_log <<
"# Removed evidence over attribute " << name << std::endl;
767 }
catch (
const std::string& msg) {
787 m_log <<
"# Starting inference over query: " <<
query <<
"... " << std::endl;
797 double t = timer.
step();
801 if (
m_verbose) {
m_log <<
"# Time in seconds (accuracy ~0.001): " << t << std::endl; }
816 auto label_value = j.
val(0);
818 float value = float(m.
get(j));
821 singleResult.
label = label;
822 singleResult.
p = value;
824 result.
values.push_back(singleResult);
834 throw "something went wrong while infering: " + e.
errorContent();
835 }
catch (
const std::string& msg) {
addError(msg); }
849 if (
m_verbose)
m_log <<
"# Building the inference engine... " << std::flush;
868 if (
m_verbose)
m_log <<
"(Grounding the network... " << std::flush;
878 grd_inf->setBNInference(bn_inf);
900 if (i >=
count())
throw "Index out of bound.";
915 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-separation).
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>
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.
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>
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.
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>.
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)
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.
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...
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.