42 #include <agrum/PRM/o3prmr/cocoR/Parser.h> 56 m_reader(new o3prm::O3prmReader<
double >()), m_bn(0), m_inf(0),
57 m_syntax_flag(false), m_verbose(false), m_log(
std::cout),
98 if (path.length() && path.back() !=
'/') { path = path +
'/'; }
150 std::string file_content =
__readFile(filename);
157 unsigned char* buffer =
new unsigned char[file_content.length() + 1];
158 strcpy((
char*)buffer, file_content.c_str());
159 Scanner s(buffer,
int(file_content.length() + 1));
161 p.setO3prmrContext(&c);
166 if (
errors() > 0) {
return false; }
173 for (
size_t i = 0; i <
m_paths.size(); i++) {
190 std::ifstream istream(file, std::ifstream::binary);
193 istream.seekg(0, istream.end);
194 int length = int(istream.tellg());
195 istream.seekg(0, istream.beg);
198 str.resize(length,
' ');
199 char* begin = &*str.begin();
201 istream.read(begin, length);
214 Scanner s((
unsigned char*)line.c_str(), (int)line.length());
216 p.setO3prmrContext(&c);
220 if (
errors() > 0)
return false;
239 m_log <<
"## Start interpretation." << std::endl << std::flush;
242 if (
errors() > 0)
return false;
245 std::vector< O3prmrSession< double >* > sessions = c->
sessions();
247 for (
const auto session : sessions)
248 for (
auto command : session->commands()) {
253 switch (command->type()) {
277 }
catch (std::string& err) {
286 m_log <<
"Errors : skip the rest of this session." << std::endl;
293 m_log <<
"## End interpretation." << std::endl << std::flush;
313 if (
errors() > 0)
return false;
316 for (
const auto command : context->
imports()) {
319 bool succeed =
import(context, command->value);
328 m_log <<
"## Check semantic for " << context->
sessions().size()
329 <<
" sessions" << std::endl;
332 for (
const auto session : context->
sessions()) {
333 std::string sessionName = session->name();
338 m_log <<
"## Start session '" << sessionName <<
"'..." << std::endl
341 for (
const auto command : session->commands()) {
343 m_log <<
"# * Going to check command : " << command->toString()
353 switch (command->type()) {
376 +
"\n -> Command not processed.");
382 }
catch (std::string& err) {
391 m_log <<
"Errors : skip the rest of this session." << std::endl;
409 <<
"## Session '" << sessionName <<
"' finished." << std::endl
436 std::string left_val = command->
leftValue;
437 const std::string right_val = command->
rightValue;
446 std::make_pair(&instance, &attr);
449 command->
chain = std::make_pair(&instance, &attr);
453 command->
potentiel.add(chain.second->type().variable());
458 if (chain.second->type().variable().label(
459 i.
val(chain.second->type().variable()))
468 if (!found)
addError(right_val +
" is not a label of " + left_val);
476 }
catch (std::string& err) {
addError(err); }
483 std::string name = command->
value;
495 command->
chain = std::make_pair(&instance, &attr);
501 }
catch (std::string& err) {
addError(err); }
508 std::string name = command->
value;
520 command->
chain = std::make_pair(&instance, &attr);
526 }
catch (std::string& err) {
addError(err); }
535 std::string import_name) {
538 m_log <<
"# Loading system '" << import_name <<
"' => '" << std::flush;
541 std::string import_package = import_name;
543 std::replace(import_name.begin(), import_name.end(),
'.',
'/');
544 import_name +=
".o3prm";
547 m_log << import_name <<
"' ... " << std::endl << std::flush;
550 std::ifstream file_test;
552 std::string import_abs_filename;
555 std::string o3prmrFilename = context->
filename();
557 if (!o3prmrFilename.empty()) {
558 size_t index = o3prmrFilename.find_last_of(
'/');
560 if (index != std::string::npos) {
561 std::string dir = o3prmrFilename.substr(0, index + 1);
562 import_abs_filename = dir + import_name;
565 m_log <<
"# Search from filedir '" << import_abs_filename
566 <<
"' ... " << std::flush;
569 file_test.open(import_abs_filename.c_str());
571 if (file_test.is_open()) {
577 m_log <<
"not found." << std::endl << std::flush;
583 std::string
package = context->package();
585 if (!found && !package.empty()) {
589 std::string filename = context->
filename();
591 if (!filename.empty()) {
592 size_t size = filename.find_last_of(
'/');
594 if (size != std::string::npos) {
595 root += filename.substr(0, size + 1);
601 int count = (int)std::count(package.begin(), package.end(),
'.');
603 for (
int i = 0; i <
count; i++)
609 m_log <<
"# Search from package '" <<
package << "' => '"
610 << import_abs_filename << "' ... " << std::flush;
613 file_test.open(import_abs_filename.c_str());
615 if (file_test.is_open()) {
621 m_log <<
"not found." << std::endl << std::flush;
626 for (
const auto& path :
m_paths) {
627 import_abs_filename = path + import_name;
630 m_log <<
"# Search from classpath '" << import_abs_filename
631 <<
"' ... " << std::flush;
634 file_test.open(import_abs_filename.c_str());
636 if (file_test.is_open()) {
637 if (
m_verbose) {
m_log <<
" found !" << std::endl << std::flush; }
643 m_log <<
" not found." << std::endl << std::flush;
664 ||
errors() > previousO3prmrError)) {
665 m_log <<
"Finished with errors." << std::endl;
667 m_log <<
"Finished." << std::endl;
678 previousO3prmError++) {
682 return errors() == previousO3prmrError;
685 if (
m_verbose) {
m_log <<
"Finished with exceptions." << std::endl; }
693 size_t dot = s.find_first_of(
'.');
694 std::string name = s.substr(0, dot);
697 if (
prm()->isSystem(name)) {
698 s = s.substr(dot + 1);
703 s = s.substr(dot + 1);
707 while (dot != std::string::npos) {
708 if (
prm()->isSystem(name)) {
709 s = s.substr(dot + 1);
713 dot = s.find(
'.', dot + 1);
714 name = s.substr(0, dot);
717 throw "could not find any system in '" + s +
"'.";
724 size_t dot = s.find_first_of(
'.');
725 std::string name = s.substr(0, dot);
728 throw "'" + name +
"' is not an instance of system '" + sys.
name()
731 s = s.substr(dot + 1);
738 throw "'" + s +
"' is not an attribute of instance '" + instance.
name()
748 }
catch (
const std::string&) {}
754 throw "could not find any system or alias in '" + ident
755 +
"' and no default alias has been set.";
774 m_log <<
"# Added evidence " << command->
rightValue <<
" over attribute " 780 addError(
"something went wrong when adding evidence " + command->rightValue
781 +
" over " + command->leftValue +
" : " + ex.
errorContent());
784 }
catch (
const std::string& msg) {
793 std::string name = command->
value;
803 m_log <<
"# Removed evidence over attribute " << name << std::endl;
808 }
catch (
const std::string& msg) {
828 m_log <<
"# Starting inference over query: " << query <<
"... " 839 double t = timer.
step();
844 m_log <<
"# Time in seconds (accuracy ~0.001): " << t << std::endl;
860 auto label_value = j.
val(0);
862 float value = float(m.
get(j));
865 singleResult.
label = label;
866 singleResult.p = value;
868 result.
values.push_back(singleResult);
879 throw "something went wrong while infering: " + e.
errorContent();
881 }
catch (
const std::string& msg) {
addError(msg); }
896 m_log <<
"# Building the inference engine... " << std::flush;
916 if (
m_verbose)
m_log <<
"(Grounding the network... " << std::flush;
926 grd_inf->setBNInference(bn_inf);
948 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
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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.
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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.
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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.
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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.
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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.
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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)
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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>
Copyright 2005-2019 Pierre-Henri WUILLEMIN et Christophe GONZALES (LIP6) {prenom.nom}_at_lip6.fr.
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