aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
O3prmrInterpreter.cpp
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2025 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2025 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
48#include <filesystem>
49
50#include <agrum/agrum.h>
51
52#include <agrum/BN/BayesNet.h>
59#include <agrum/PRM/o3prmr/cocoR/Parser.h>
61
62namespace gum {
63
64 namespace prm {
65
66 namespace o3prmr {
67
68 /* **************************************************************************
69 */
70
73 m_context(new O3prmrContext< double >()), m_reader(new o3prm::O3prmReader< double >()),
74 m_bn(0), m_inf(0), m_syntax_flag(false), m_verbose(false), m_log(std::cout),
75 m_current_line(-1) {}
76
79 delete m_context;
80 if (m_bn) { delete m_bn; }
81 for (auto p: m_inf_map) {
82 delete p.second;
83 }
84 delete m_reader->prm();
85 delete m_reader;
86 }
87
88 /* **************************************************************************
89 */
90
93
96 delete m_context;
97
98 if (context == 0) m_context = new O3prmrContext< double >();
99 else m_context = context;
100 }
101
104 std::vector< std::string > O3prmrInterpreter::getPaths() const { return m_paths; }
105
108 void O3prmrInterpreter::addPath(std::string path) {
109 if (path.length() && path.back() != '/') { path = path + '/'; }
110
111 std::filesystem::directory_entry dir(path);
112 if (dir.exists()) {
113 m_paths.push_back(path);
114 } else {
115 GUM_ERROR(NotFound, "not a directory")
116 }
117 }
118
122
125
128
131
134
136 const PRM< double >* O3prmrInterpreter::prm() const { return m_reader->prm(); }
137
140
144 const std::vector< QueryResult >& O3prmrInterpreter::results() const { return m_results; }
145
153 bool O3prmrInterpreter::interpretFile(const std::string& filename) {
154 m_results.clear();
155
156 try {
157 std::string file_content = _readFile_(filename);
158
159 delete m_context;
160 m_context = new O3prmrContext< double >(filename);
161 O3prmrContext< double > c(filename);
162
163 // On vérifie la syntaxe
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));
167 Parser p(&s);
168 p.setO3prmrContext(&c);
169 p.Parse();
170
171 m_errors = p.errors();
172
173 if (errors() > 0) { return false; }
174
175 // Set paths to search from.
176 delete m_reader->prm();
177 delete m_reader;
179
180 for (size_t i = 0; i < m_paths.size(); i++) {
181 m_reader->addClassPath(m_paths[i]);
182 }
183
184 // On vérifie la sémantique.
185 if (!checkSemantic(&c)) { return false; }
186
187 if (isInSyntaxMode()) {
188 return true;
189 } else {
190 return interpret(&c);
191 }
192 } catch (gum::Exception&) { return false; }
193 }
194
195 std::string O3prmrInterpreter::_readFile_(const std::string& file) {
196 // read entire file into string
197 std::ifstream istream(file, std::ifstream::binary);
198 if (istream) {
199 // get length of file:
200 istream.seekg(0, istream.end);
201 int length = int(istream.tellg());
202 istream.seekg(0, istream.beg);
203
204 std::string str;
205 str.resize(length, ' '); // reserve space
206 char* begin = &*str.begin();
207
208 istream.read(begin, length);
209 istream.close();
210
211 return str;
212 }
213 GUM_ERROR(OperationNotAllowed, "Could not open file")
214 }
215
216 bool O3prmrInterpreter::interpretLine(const std::string& line) {
217 m_results.clear();
218
219 // On vérifie la syntaxe
221 Scanner s((unsigned char*)line.c_str(), (int)line.length());
222 Parser p(&s);
223 p.setO3prmrContext(&c);
224 p.Parse();
225 m_errors = p.errors();
226
227 if (errors() > 0) return false;
228
229 // On vérifie la sémantique.
230 if (!checkSemantic(&c)) return false;
231
232 if (isInSyntaxMode()) return true;
233 else return interpret(&c);
234 }
235
243 if (isVerboseMode()) m_log << "## Start interpretation." << std::endl << std::flush;
244
245 // Don't parse if any syntax errors.
246 if (errors() > 0) return false;
247
248 // For each session
249 std::vector< O3prmrSession< double >* > sessions = c->sessions();
250
251 for (const auto session: sessions)
252 for (auto command: session->commands()) {
253 // We process it.
254 bool result = true;
255
256 try {
257 switch (command->type()) {
259 result = observe((ObserveCommand< double >*)command);
260 break;
261
263 result = unobserve((UnobserveCommand< double >*)command);
264 break;
265
267 setEngine((SetEngineCommand*)command);
268 break;
269
272 break;
273
275 query((QueryCommand< double >*)command);
276 break;
277 }
278 } catch (Exception& err) {
279 result = false;
280 addError(err.errorContent());
281 } catch (std::string& err) {
282 result = false;
283 addError(err);
284 }
285
286 // If there was a problem, skip the rest of this session,
287 // unless syntax mode is activated.
288 if (!result) {
289 if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
290
291 break;
292 }
293 }
294
295 if (isVerboseMode()) m_log << "## End interpretation." << std::endl << std::flush;
296
297 return errors() == 0;
298 }
299
300 /* **************************************************************************
301 */
302
314 // Don't parse if any syntax errors.
315 if (errors() > 0) return false;
316
317 // On importe tous les systèmes.
318 for (const auto command: context->imports()) {
319 m_current_line = command->line;
320 // if import doen't succed stop here unless syntax mode is activated.
321 bool succeed = import(context, command->value);
322
323 if (!succeed && !isInSyntaxMode()) return false;
324
325 // En cas de succès, on met à jour le contexte global
326 if (succeed) m_context->addImport(*command);
327 }
328
329 if (m_verbose)
330 m_log << "## Check semantic for " << context->sessions().size() << " sessions"
331 << std::endl;
332
333 // On vérifie chaque session
334 for (const auto session: context->sessions()) {
335 std::string sessionName = session->name();
336 O3prmrSession< double >* new_session = new O3prmrSession< double >(sessionName);
337
338 if (m_verbose)
339 m_log << "## Start session '" << sessionName << "'..." << std::endl << std::endl;
340
341 for (const auto command: session->commands()) {
342 if (m_verbose)
343 m_log << "# * Going to check command : " << command->toString() << std::endl;
344
345 // Update the current line (for warnings and errors)
346 m_current_line = command->line;
347
348 // We check it.
349 bool result = true;
350
351 try {
352 switch (command->type()) {
354 result = checkSetEngine((SetEngineCommand*)command);
355 break;
356
358 result = checkSetGndEngine((SetGndEngineCommand*)command);
359 break;
360
362 result = checkObserve((ObserveCommand< double >*)command);
363 break;
364
366 result = checkUnobserve((UnobserveCommand< double >*)command);
367 break;
368
370 result = checkQuery((QueryCommand< double >*)command);
371 break;
372
373 default :
374 addError("Error : Unknow command : " + command->toString()
375 + "\n -> Command not processed.");
376 result = false;
377 }
378 } catch (Exception& err) {
379 result = false;
380 addError(err.errorContent());
381 } catch (std::string& err) {
382 result = false;
383 addError(err);
384 }
385
386 // If there was a problem, skip the rest of this session,
387 // unless syntax mode is activated.
388 if (!result && !isInSyntaxMode()) {
389 if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
390
391 break;
392 }
393
394 // On l'ajoute au contexte globale
395 if (result) new_session->addCommand((const O3prmrCommand*)command);
396 }
397
398 // Ajoute la session au contexte global,
399 // ou à la dernière session.
400 if (sessionName == "default" && m_context->sessions().size() > 0)
401 *(m_context->sessions().back()) += *new_session;
402 else m_context->addSession(*new_session);
403
404 if (m_verbose)
405 m_log << std::endl
406 << "## Session '" << sessionName << "' finished." << std::endl
407 << std::endl
408 << std::endl;
409
410 // todo : check memory leak
411 // delete new_session; ??
412 }
413
414 if (isVerboseMode() && errors() != 0) m_errors.elegantErrorsAndWarnings(m_log);
415
416 return errors() == 0;
417 }
418
420 m_engine = command->value;
421 return m_engine == "SVED" || m_engine == "GRD" || m_engine == "SVE";
422 }
423
425 m_bn_engine = command->value;
426 return m_bn_engine == "VE" || m_bn_engine == "VEBB" || m_bn_engine == "lazy";
427 }
428
430 try {
431 std::string left_val = command->leftValue;
432 const std::string right_val = command->rightValue;
433
434 // Contruct the pair (instance,attribut)
435 const PRMSystem< double >& sys = system(left_val);
436 const PRMInstance< double >& instance = sys.get(findInstanceName(left_val, sys));
437 const PRMAttribute< double >& attr = instance.get(findAttributeName(left_val, instance));
438 typename PRMInference< double >::Chain chain = std::make_pair(&instance, &attr);
439
440 command->system = &sys;
441 command->chain = std::make_pair(&instance, &attr);
442
443 // Check label exists for this type.
444 // Tensor<double> e;
445 command->potentiel.add(chain.second->type().variable());
446 Instantiation i(command->potentiel);
447 bool found = false;
448
449 for (i.setFirst(); !i.end(); i.inc()) {
450 if (chain.second->type().variable().label(i.val(chain.second->type().variable()))
451 == right_val) {
452 command->potentiel.set(i, (double)1.0);
453 found = true;
454 } else {
455 command->potentiel.set(i, (double)0.0);
456 }
457 }
458
459 if (!found) addError(right_val + " is not a label of " + left_val);
460
461 // else command->potentiel = e;
462
463 return found;
464
465 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
466 addError(err);
467 }
468
469 return false;
470 }
471
473 try {
474 std::string name = command->value;
475
476 // Contruct the pair (instance,attribut)
477 const PRMSystem< double >& sys = system(name);
478 const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
479 const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
480 // PRMInference<double>::Chain chain = std::make_pair(&instance,
481 // &attr);
482
483 command->system = &sys;
484 command->chain = std::make_pair(&instance, &attr);
485
486 return true;
487
488 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
489 addError(err);
490 }
491
492 return false;
493 }
494
496 try {
497 std::string name = command->value;
498
499 // Contruct the pair (instance,attribut)
500 const PRMSystem< double >& sys = system(name);
501 const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
502 const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
503 // PRMInference<double>::Chain chain = std::make_pair(&instance,
504 // &attr);
505
506 command->system = &sys;
507 command->chain = std::make_pair(&instance, &attr);
508
509 return true;
510
511 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
512 addError(err);
513 }
514
515 return false;
516 }
517
518 // Import the system o3prm file
519 // Return false if any error.
520
521 bool O3prmrInterpreter::import(O3prmrContext< double >* context, std::string import_name) {
522 try {
523 if (m_verbose) { m_log << "# Loading system '" << import_name << "' => '" << std::flush; }
524
525 std::string import_package = import_name;
526
527 std::replace(import_name.begin(), import_name.end(), '.', '/');
528 import_name += ".o3prm";
529
530 if (m_verbose) { m_log << import_name << "' ... " << std::endl << std::flush; }
531
532 std::ifstream file_test;
533 bool found = false;
534 std::string import_abs_filename;
535
536 // Search in o3prmr file dir.
537 std::string o3prmrFilename = context->filename();
538
539 if (!o3prmrFilename.empty()) {
540 size_t index = o3prmrFilename.find_last_of('/');
541
542 if (index != std::string::npos) {
543 std::string dir = o3prmrFilename.substr(0, index + 1);
544 import_abs_filename = dir + import_name;
545
546 if (m_verbose) {
547 m_log << "# Search from filedir '" << import_abs_filename << "' ... " << std::flush;
548 }
549
550 file_test.open(import_abs_filename.c_str());
551
552 if (file_test.is_open()) {
553 if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
554
555 file_test.close();
556 found = true;
557 } else if (m_verbose) {
558 m_log << "not found." << std::endl << std::flush;
559 }
560 }
561 }
562
563 // Deduce root path from package name.
564 std::string package = context->package();
565
566 if (!found && !package.empty()) {
567 std::string root;
568
569 // if filename is not empty, start from it.
570 std::string filename = context->filename();
571
572 if (!filename.empty()) {
573 size_t size = filename.find_last_of('/');
574
575 if (size != std::string::npos) {
576 root += filename.substr(0, size + 1); // take with the '/'
577 }
578 }
579
580 //
581 root += "../";
582 int count = (int)std::count(package.begin(), package.end(), '.');
583
584 for (int i = 0; i < count; i++)
585 root += "../";
586
587 import_abs_filename = std::filesystem::absolute(std::filesystem::path(root)
588 / std::filesystem::path(import_name))
589 .string();
590
591 if (m_verbose) {
592 m_log << "# Search from package '" << package << "' => '" << import_abs_filename
593 << "' ... " << std::flush;
594 }
595
596 file_test.open(import_abs_filename.c_str());
597
598 if (file_test.is_open()) {
599 if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
600
601 file_test.close();
602 found = true;
603 } else if (m_verbose) {
604 m_log << "not found." << std::endl << std::flush;
605 }
606 }
607
608 // Search import in all paths.
609 for (const auto& path: m_paths) {
610 import_abs_filename = path + import_name;
611
612 if (m_verbose) {
613 m_log << "# Search from classpath '" << import_abs_filename << "' ... " << std::flush;
614 }
615
616 file_test.open(import_abs_filename.c_str());
617
618 if (file_test.is_open()) {
619 if (m_verbose) { m_log << " found !" << std::endl << std::flush; }
620
621 file_test.close();
622 found = true;
623 break;
624 } else if (m_verbose) {
625 m_log << " not found." << std::endl << std::flush;
626 }
627 }
628
629 if (!found) {
630 if (m_verbose) { m_log << "Finished with errors." << std::endl; }
631
632 addError("import not found.");
633 return false;
634 }
635
636 // May throw std::IOError if file does't exist
637 Size previousO3prmError = m_reader->errors();
638 Size previousO3prmrError = errors();
639
640 try {
641 m_reader->readFile(import_abs_filename, import_package);
642
643 // Show errors and warning
644 if (m_verbose
645 && (m_reader->errors() > (unsigned int)previousO3prmError
646 || errors() > previousO3prmrError)) {
647 m_log << "Finished with errors." << std::endl;
648 } else if (m_verbose) {
649 m_log << "Finished." << std::endl;
650 }
651
652 } catch (const IOError& err) {
653 if (m_verbose) { m_log << "Finished with errors." << std::endl; }
654
655 addError(err.errorContent());
656 }
657
658 // Add o3prm errors and warnings to o3prmr errors
659 for (; previousO3prmError < m_reader->errorsContainer().count(); previousO3prmError++) {
660 m_errors.add(m_reader->errorsContainer().error(previousO3prmError));
661 }
662
663 return errors() == previousO3prmrError;
664
665 } catch (const Exception& err) {
666 if (m_verbose) { m_log << "Finished with exceptions." << std::endl; }
667
668 addError(err.errorContent());
669 return false;
670 }
671 }
672
673 std::string O3prmrInterpreter::findSystemName(std::string& s) {
674 size_t dot = s.find_first_of('.');
675 std::string name = s.substr(0, dot);
676
677 // We look first for real system, next for alias.
678 if (prm()->isSystem(name)) {
679 s = s.substr(dot + 1);
680 return name;
681 }
682
683 if (!m_context->aliasToImport(name).empty()) {
684 s = s.substr(dot + 1);
685 return m_context->aliasToImport(name);
686 }
687
688 while (dot != std::string::npos) {
689 if (prm()->isSystem(name)) {
690 s = s.substr(dot + 1);
691 return name;
692 }
693
694 dot = s.find('.', dot + 1);
695 name = s.substr(0, dot);
696 }
697
698 throw "could not find any system in '" + s + "'.";
699 }
700
701 std::string O3prmrInterpreter::findInstanceName(std::string& s,
702 const PRMSystem< double >& sys) {
703 // We have found system before, so 's' has been stripped.
704 size_t dot = s.find_first_of('.');
705 std::string name = s.substr(0, dot);
706
707 if (!sys.exists(name))
708 throw "'" + name + "' is not an instance of system '" + sys.name() + "'.";
709
710 s = s.substr(dot + 1);
711 return name;
712 }
713
714 std::string O3prmrInterpreter::findAttributeName(const std::string& s,
715 const PRMInstance< double >& instance) {
716 if (!instance.exists(s))
717 throw "'" + s + "' is not an attribute of instance '" + instance.name() + "'.";
718
719 return s;
720 }
721
722 // After this method, ident doesn't contains the system name anymore.
724 try {
725 return prm()->getSystem(findSystemName(ident));
726 } catch (const std::string&) {}
727
728 if ((m_context->mainImport() != 0) && prm()->isSystem(m_context->mainImport()->value))
729 return prm()->getSystem(m_context->mainImport()->value);
730
731 throw "could not find any system or alias in '" + ident
732 + "' and no default alias has been set.";
733 }
734
736
738 const typename PRMInference< double >::Chain& chain = command->chain;
739
740 // Generate the inference engine if it doesn't exist.
741 if (!m_inf) { generateInfEngine(*(command->system)); }
742
743 // Prevent from something
744 if (m_inf->hasEvidence(chain)) addWarning(command->leftValue + " is already observed");
745
746 m_inf->addEvidence(chain, command->potentiel);
747
748 if (m_verbose)
749 m_log << "# Added evidence " << command->rightValue << " over attribute "
750 << command->leftValue << std::endl;
751
752 return true;
753
754 } catch (OperationNotAllowed& ex) {
755 addError("something went wrong when adding evidence " + command->rightValue + " over "
756 + command->leftValue + " : " + ex.errorContent());
757 return false;
758
759 } catch (const std::string& msg) {
760 addError(msg);
761 return false;
762 }
763
765
767 std::string name = command->value;
768 typename PRMInference< double >::Chain chain = command->chain;
769
770 // Prevent from something
771 if (!m_inf || !m_inf->hasEvidence(chain)) {
772 addWarning(name + " was not observed");
773 } else {
774 m_inf->removeEvidence(chain);
775
776 if (m_verbose) m_log << "# Removed evidence over attribute " << name << std::endl;
777 }
778
779 return true;
780
781 } catch (const std::string& msg) {
782 addError(msg);
783 return false;
784 }
785
788 const std::string& query = command->value;
789
790 if (m_inf_map.exists(command->system)) {
791 m_inf = m_inf_map[command->system];
792 } else {
793 m_inf = nullptr;
794 }
795
796 // Create inference engine if it has not been already created.
797 if (!m_inf) { generateInfEngine(*(command->system)); }
798
799 // Inference
800 if (m_verbose) {
801 m_log << "# Starting inference over query: " << query << "... " << std::endl;
802 }
803
804 Timer timer;
805 timer.reset();
806
808 m_inf->posterior(command->chain, m);
809
810 // Compute spent time
811 double t = timer.step();
812
813 if (m_verbose) { m_log << "Finished." << std::endl; }
814
815 if (m_verbose) { m_log << "# Time in seconds (accuracy ~0.001): " << t << std::endl; }
816
817 // Show results
818
819 if (m_verbose) { m_log << std::endl; }
820
821 QueryResult result;
822 result.command = query;
823 result.time = t;
824
825 Instantiation j(m);
826 const PRMAttribute< double >& attr = *(command->chain.second);
827
828 for (j.setFirst(); !j.end(); j.inc()) {
829 // auto label_value = j.val ( attr.type().variable() );
830 auto label_value = j.val(0);
831 std::string label = attr.type().variable().label(label_value);
832 float value = float(m.get(j));
833
834 SingleResult singleResult;
835 singleResult.label = label;
836 singleResult.p = value;
837
838 result.values.push_back(singleResult);
839
840 if (m_verbose) { m_log << label << " : " << value << std::endl; }
841 }
842
843 m_results.push_back(result);
844
845 if (m_verbose) { m_log << std::endl; }
846
847 } catch (Exception& e) {
848 GUM_SHOWERROR(e);
849 throw "something went wrong while infering: " + e.errorContent();
850
851 } catch (const std::string& msg) { addError(msg); }
852
855 m_engine = command->value;
856 }
857
860 m_bn_engine = command->value;
861 }
862
865 if (m_verbose) m_log << "# Building the inference engine... " << std::flush;
866
867 //
868 if (m_engine == "SVED") {
869 m_inf = new SVED< double >(*(prm()), sys);
870
871 //
872 } else if (m_engine == "SVE") {
873 m_inf = new SVE< double >(*(prm()), sys);
874
875 } else {
876 if (m_engine != "GRD") {
877 addWarning("unkown engine '" + m_engine + "', use GRD insteed.");
878 }
879
880 MarginalTargetedInference< double >* bn_inf = nullptr;
881 if (m_bn) { delete m_bn; }
882 m_bn = new BayesNet< double >();
884
885 if (m_verbose) m_log << "(Grounding the network... " << std::flush;
886
887 sys.groundedBN(bn_factory);
888
889 if (m_verbose) m_log << "Finished)" << std::flush;
890
891 // bn_inf = new LazyPropagation<double>( *m_bn );
893
894 auto grd_inf = new GroundedInference< double >(*(prm()), sys);
895 grd_inf->setBNInference(bn_inf);
896 m_inf = grd_inf;
897 }
898
899 m_inf_map.insert(&sys, m_inf);
900 if (m_verbose) m_log << "Finished." << std::endl;
901 }
902
903 /* **************************************************************************
904 */
905
907 Size O3prmrInterpreter::count() const { return m_errors.count(); }
908
910 Size O3prmrInterpreter::errors() const { return m_errors.error_count; }
911
913 Size O3prmrInterpreter::warnings() const { return m_errors.warning_count; }
914
917 if (i >= count()) throw "Index out of bound.";
918
919 return m_errors.error(i);
920 }
921
924
926 void O3prmrInterpreter::showElegantErrors(std::ostream& o) const {
927 m_errors.elegantErrors(o);
928 }
929
932 m_errors.elegantErrorsAndWarnings(o);
933 }
934
936 void O3prmrInterpreter::showErrorCounts(std::ostream& o) const {
937 m_errors.syntheticResults(o);
938 }
939
940 /* **************************************************************************
941 */
942
944 void O3prmrInterpreter::addError(std::string msg) {
945 m_errors.addError(msg, m_context->filename(), m_current_line, 0);
946
947 if (m_verbose) m_log << m_errors.last().toString() << std::endl;
948 }
949
951 void O3prmrInterpreter::addWarning(std::string msg) {
952 m_errors.addWarning(msg, m_context->filename(), m_current_line, 0);
953
954 if (m_verbose) m_log << m_errors.last().toString() << std::endl;
955 }
956
957 } // namespace o3prmr
958 } // namespace prm
959} // namespace gum
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.
Definition exceptions.h:118
GUM_NODISCARD std::string errorContent() const
Returns the message content.
Definition exceptions.h:144
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.
Definition tensor.h:85
Class used to compute response times for benchmark purposes.
Definition timer.h:69
void reset()
Reset the timer.
Definition timer_inl.h:52
double step() const
Returns the delta time between now and the last reset() call (or the constructor).
Definition timer_inl.h:71
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.
Definition PRMType_inl.h:64
PRMSystem< GUM_SCALAR > & getSystem(const std::string &name)
Returns a constant reference on a PRMSystem<GUM_SCALAR> given it's name.
Definition PRM_tpl.h:161
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
Definition SVED.h:72
This class is an implementation of the Structured Variable Elimination algorithm on PRM<GUM_SCALAR>.
Definition SVE.h:72
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
~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
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
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
Size count() const
En cas d'échec, l'API de gestion d'erreurs est présente.
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
const PRMSystem< GUM_SCALAR > * system
PRMInference< GUM_SCALAR >::Chain chain
std::vector< SingleResult > values
PRMInference< GUM_SCALAR >::Chain chain
const PRMSystem< GUM_SCALAR > * system
#define GUM_ERROR(type, msg)
Definition exceptions.h:72
#define GUM_SHOWERROR(e)
Definition exceptions.h:85
Headers of GroundedInference.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size Idx
Type for indexes.
Definition types.h:79
Implementation of a Shafer-Shenoy's-like version of lazy propagation for inference in Bayesian networ...
namespace for all probabilistic relational models entities
Definition agrum.h:68
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
STL namespace.
Implementation of a variable elimination algorithm for inference in Bayesian networks.