39 #include <agrum/PRM/o3prmr/cocoR/Parser.h> 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),
95 if (path.length() && path.back() !=
'/') { path = path +
'/'; }
147 std::string file_content =
__readFile(filename);
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));
158 p.setO3prmrContext(&c);
163 if (
errors() > 0) {
return false; }
170 for (
size_t i = 0; i <
m_paths.size(); i++) {
187 std::ifstream istream(file, std::ifstream::binary);
190 istream.seekg(0, istream.end);
191 int length = int(istream.tellg());
192 istream.seekg(0, istream.beg);
195 str.resize(length,
' ');
196 char* begin = &*str.begin();
198 istream.read(begin, length);
211 Scanner s((
unsigned char*)line.c_str(), (int)line.length());
213 p.setO3prmrContext(&c);
217 if (
errors() > 0)
return false;
236 m_log <<
"## Start interpretation." << std::endl << std::flush;
239 if (
errors() > 0)
return false;
242 std::vector< O3prmrSession< double >* > sessions = c->
sessions();
244 for (
const auto session : sessions)
245 for (
auto command : session->commands()) {
250 switch (command->type()) {
274 }
catch (std::string& err) {
283 m_log <<
"Errors : skip the rest of this session." << std::endl;
290 m_log <<
"## End interpretation." << std::endl << std::flush;
310 if (
errors() > 0)
return false;
313 for (
const auto command : context->
imports()) {
316 bool succeed =
import(context, command->value);
325 m_log <<
"## Check semantic for " << context->
sessions().size()
326 <<
" sessions" << std::endl;
329 for (
const auto session : context->
sessions()) {
330 std::string sessionName = session->name();
335 m_log <<
"## Start session '" << sessionName <<
"'..." << std::endl
338 for (
const auto command : session->commands()) {
340 m_log <<
"# * Going to check command : " << command->toString()
350 switch (command->type()) {
373 +
"\n -> Command not processed.");
379 }
catch (std::string& err) {
388 m_log <<
"Errors : skip the rest of this session." << std::endl;
406 <<
"## Session '" << sessionName <<
"' finished." << std::endl
433 std::string left_val = command->
leftValue;
434 const std::string right_val = command->
rightValue;
443 std::make_pair(&instance, &attr);
446 command->
chain = std::make_pair(&instance, &attr);
450 command->
potentiel.add(chain.second->type().variable());
455 if (chain.second->type().variable().label(
456 i.
val(chain.second->type().variable()))
465 if (!found)
addError(right_val +
" is not a label of " + left_val);
473 }
catch (std::string& err) {
addError(err); }
480 std::string name = command->
value;
492 command->
chain = std::make_pair(&instance, &attr);
498 }
catch (std::string& err) {
addError(err); }
505 std::string name = command->
value;
517 command->
chain = std::make_pair(&instance, &attr);
523 }
catch (std::string& err) {
addError(err); }
532 std::string import_name) {
535 m_log <<
"# Loading system '" << import_name <<
"' => '" << std::flush;
538 std::string import_package = import_name;
540 std::replace(import_name.begin(), import_name.end(),
'.',
'/');
541 import_name +=
".o3prm";
544 m_log << import_name <<
"' ... " << std::endl << std::flush;
547 std::ifstream file_test;
549 std::string import_abs_filename;
552 std::string o3prmrFilename = context->
filename();
554 if (!o3prmrFilename.empty()) {
555 size_t index = o3prmrFilename.find_last_of(
'/');
557 if (index != std::string::npos) {
558 std::string dir = o3prmrFilename.substr(0, index + 1);
559 import_abs_filename = dir + import_name;
562 m_log <<
"# Search from filedir '" << import_abs_filename
563 <<
"' ... " << std::flush;
566 file_test.open(import_abs_filename.c_str());
568 if (file_test.is_open()) {
574 m_log <<
"not found." << std::endl << std::flush;
580 std::string
package = context->package();
582 if (!found && !package.empty()) {
586 std::string filename = context->
filename();
588 if (!filename.empty()) {
589 size_t size = filename.find_last_of(
'/');
591 if (size != std::string::npos) {
592 root += filename.substr(0, size + 1);
598 int count = (int)std::count(package.begin(), package.end(),
'.');
600 for (
int i = 0; i <
count; i++)
606 m_log <<
"# Search from package '" <<
package << "' => '"
607 << import_abs_filename << "' ... " << std::flush;
610 file_test.open(import_abs_filename.c_str());
612 if (file_test.is_open()) {
618 m_log <<
"not found." << std::endl << std::flush;
623 for (
const auto& path :
m_paths) {
624 import_abs_filename = path + import_name;
627 m_log <<
"# Search from classpath '" << import_abs_filename
628 <<
"' ... " << std::flush;
631 file_test.open(import_abs_filename.c_str());
633 if (file_test.is_open()) {
634 if (
m_verbose) {
m_log <<
" found !" << std::endl << std::flush; }
640 m_log <<
" not found." << std::endl << std::flush;
661 ||
errors() > previousO3prmrError)) {
662 m_log <<
"Finished with errors." << std::endl;
664 m_log <<
"Finished." << std::endl;
675 previousO3prmError++) {
679 return errors() == previousO3prmrError;
682 if (
m_verbose) {
m_log <<
"Finished with exceptions." << std::endl; }
690 size_t dot = s.find_first_of(
'.');
691 std::string name = s.substr(0, dot);
694 if (
prm()->isSystem(name)) {
695 s = s.substr(dot + 1);
700 s = s.substr(dot + 1);
704 while (dot != std::string::npos) {
705 if (
prm()->isSystem(name)) {
706 s = s.substr(dot + 1);
710 dot = s.find(
'.', dot + 1);
711 name = s.substr(0, dot);
714 throw "could not find any system in '" + s +
"'.";
721 size_t dot = s.find_first_of(
'.');
722 std::string name = s.substr(0, dot);
725 throw "'" + name +
"' is not an instance of system '" + sys.
name()
728 s = s.substr(dot + 1);
735 throw "'" + s +
"' is not an attribute of instance '" + instance.
name()
745 }
catch (
const std::string&) {}
751 throw "could not find any system or alias in '" + ident
752 +
"' and no default alias has been set.";
771 m_log <<
"# Added evidence " << command->
rightValue <<
" over attribute " 777 addError(
"something went wrong when adding evidence " + command->rightValue
778 +
" over " + command->leftValue +
" : " + ex.
errorContent());
781 }
catch (
const std::string& msg) {
790 std::string name = command->
value;
800 m_log <<
"# Removed evidence over attribute " << name << std::endl;
805 }
catch (
const std::string& msg) {
825 m_log <<
"# Starting inference over query: " << query <<
"... " 836 double t = timer.
step();
841 m_log <<
"# Time in seconds (accuracy ~0.001): " << t << std::endl;
857 auto label_value = j.
val(0);
859 float value = float(m.
get(j));
862 singleResult.
label = label;
863 singleResult.p = value;
865 result.
values.push_back(singleResult);
876 throw "something went wrong while infering: " + e.
errorContent();
878 }
catch (
const std::string& msg) {
addError(msg); }
893 m_log <<
"# Building the inference engine... " << std::flush;
913 if (
m_verbose)
m_log <<
"(Grounding the network... " << std::flush;
923 grd_inf->setBNInference(bn_inf);
945 if (i >=
count())
throw "Index out of bound.";
void showElegantErrors(std::ostream &o=std::cerr) const
send on std::cerr the list of errors
aGrUM's Potential is a multi-dimensional array with tensor operators.
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 './' and one is calculate from request package ...
void generateInfEngine(const gum::prm::PRMSystem< double > &sys)
Cross-platform directory utility.
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).
DiscreteVariable & variable()
Return a reference on the DiscreteVariable contained in this.
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'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.
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.
gum::BayesNet< double > * m_bn
virtual PRMType & type()=0
See gum::PRMClassElement::type().
An PRMInstance is a Bayesian Network fragment defined by a Class and used in a PRMSystem.
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()
bool checkSemantic(O3prmrContext< double > *context)
Check semantic validity of context.
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
std::string toString() const
Return a std::string representation of this gum::ParseError.
Size errors() const
of errors
bool checkQuery(QueryCommand< double > *command)
std::string filename() const
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.
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'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.
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
std::vector< SingleResult > values
bool isSystem(const std::string &name) const
PRMSystem< GUM_SCALAR > & getSystem(const std::string &name)
Returns a constant reference on a PRMSystem<GUM_SCALAR> given it's name.
This file contains abstract class definitions for Bayesian networks inference classes.
bool interpret(O3prmrContext< double > *c)
Crée le prm correspondant au contexte courant.
Size warnings() const
of warnings
gum::ErrorsContainer m_errors
Base class for all aGrUM's exceptions.
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 './' 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't process anything, just check syntax.
This is an abstract class.
Class for assigning/browsing values to tuples of discrete variables.
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)
void addError(std::string msg)
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.
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'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.
Class used to compute response times for benchmark purposesThis class represents a classic timer...
Size Idx
Type for indexes.
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's-like version of lazy propagation for inference in Bayesian Networ...
void addWarning(std::string msg)
std::size_t Size
In aGrUM, hashed values are unsigned long int.
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.
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's elt.
bool hasEvidence(const PRMInstance< GUM_SCALAR > &i) const
Returns true if i has evidence.
Size count() const
En cas d'échec, l'API de gestion d'erreurs est présente.
PRMInference< GUM_SCALAR >::Chain chain
const std::string errorContent() const
Returns the message content.
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)
<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>...
A factory class to ease BayesNet construction.
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