aGrUM 3.1.1
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-2026 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-2026 *
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 namespace prm {
64 namespace o3prmr {
65 /* **************************************************************************
66 */
67
70 m_context(new O3prmrContext< double >()), m_reader(new o3prm::O3prmReader< double >()),
71 m_bn(0), m_inf(0), m_syntax_flag(false), m_verbose(false), m_log(std::cout),
72 m_current_line(-1) {}
73
76 delete m_context;
77 if (m_bn) { delete m_bn; }
78 for (auto p: m_inf_map) {
79 delete p.second;
80 }
81 delete m_reader->prm();
82 delete m_reader;
83 }
84
85 /* **************************************************************************
86 */
87
90
93 delete m_context;
94
95 if (context == 0) m_context = new O3prmrContext< double >();
96 else m_context = context;
97 }
98
101 std::vector< std::string > O3prmrInterpreter::getPaths() const { return m_paths; }
102
105 void O3prmrInterpreter::addPath(std::string path) {
106 if (path.length() && path.back() != '/') { path = path + '/'; }
107
108 std::filesystem::directory_entry dir(path);
109 if (dir.exists()) {
110 m_paths.push_back(path);
111 } else {
112 GUM_ERROR(NotFound, "not a directory")
113 }
114 }
115
119
122
125
128
131
133 const PRM< double >* O3prmrInterpreter::prm() const { return m_reader->prm(); }
134
137
141 const std::vector< QueryResult >& O3prmrInterpreter::results() const { return m_results; }
142
150 bool O3prmrInterpreter::interpretFile(std::string_view filename) {
151 m_results.clear();
152
153 try {
154 std::string file_content = _readFile_(filename);
155
156 delete m_context;
157 m_context = new O3prmrContext< double >(std::string(filename));
158 O3prmrContext< double > c{std::string(filename)};
159
160 // On vérifie la syntaxe
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));
164 Parser p(&s);
165 p.setO3prmrContext(&c);
166 p.Parse();
167
168 m_errors = p.errors();
169
170 if (errors() > 0) { return false; }
171
172 // Set paths to search from.
173 delete m_reader->prm();
174 delete m_reader;
176
177 for (size_t i = 0; i < m_paths.size(); i++) {
178 m_reader->addClassPath(m_paths[i]);
179 }
180
181 // On vérifie la sémantique.
182 if (!checkSemantic(&c)) { return false; }
183
184 if (isInSyntaxMode()) {
185 return true;
186 } else {
187 return interpret(&c);
188 }
189 } catch (gum::Exception&) { return false; }
190 }
191
192 std::string O3prmrInterpreter::_readFile_(std::string_view file) {
193 // read entire file into string
194 std::ifstream istream(std::string(file), std::ifstream::binary);
195 if (istream) {
196 // get length of file:
197 istream.seekg(0, istream.end);
198 int length = int(istream.tellg());
199 istream.seekg(0, istream.beg);
200
201 std::string str;
202 str.resize(length, ' '); // reserve space
203 char* begin = &*str.begin();
204
205 istream.read(begin, length);
206 istream.close();
207
208 return str;
209 }
210 GUM_ERROR(OperationNotAllowed, "Could not open file")
211 }
212
213 bool O3prmrInterpreter::interpretLine(std::string_view line) {
214 m_results.clear();
215
216 // On vérifie la syntaxe
218 Scanner s((unsigned char*)line.data(), (int)line.length());
219 Parser p(&s);
220 p.setO3prmrContext(&c);
221 p.Parse();
222 m_errors = p.errors();
223
224 if (errors() > 0) return false;
225
226 // On vérifie la sémantique.
227 if (!checkSemantic(&c)) return false;
228
229 if (isInSyntaxMode()) return true;
230 else return interpret(&c);
231 }
232
240 if (isVerboseMode()) m_log << "## Start interpretation." << std::endl << std::flush;
241
242 // Don't parse if any syntax errors.
243 if (errors() > 0) return false;
244
245 // For each session
246 std::vector< O3prmrSession< double >* > sessions = c->sessions();
247
248 for (const auto session: sessions)
249 for (auto command: session->commands()) {
250 // We process it.
251 bool result = true;
252
253 try {
254 switch (command->type()) {
256 result = observe((ObserveCommand< double >*)command);
257 break;
258
260 result = unobserve((UnobserveCommand< double >*)command);
261 break;
262
264 setEngine((SetEngineCommand*)command);
265 break;
266
269 break;
270
272 query((QueryCommand< double >*)command);
273 break;
274 }
275 } catch (Exception& err) {
276 result = false;
277 addError(err.errorContent());
278 } catch (std::string& err) {
279 result = false;
280 addError(err);
281 }
282
283 // If there was a problem, skip the rest of this session,
284 // unless syntax mode is activated.
285 if (!result) {
286 if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
287
288 break;
289 }
290 }
291
292 if (isVerboseMode()) m_log << "## End interpretation." << std::endl << std::flush;
293
294 return errors() == 0;
295 }
296
297 /* **************************************************************************
298 */
299
311 // Don't parse if any syntax errors.
312 if (errors() > 0) return false;
313
314 // On importe tous les systèmes.
315 for (const auto command: context->imports()) {
316 m_current_line = command->line;
317 // if import doen't succed stop here unless syntax mode is activated.
318 bool succeed = import(context, command->value);
319
320 if (!succeed && !isInSyntaxMode()) return false;
321
322 // En cas de succès, on met à jour le contexte global
323 if (succeed) m_context->addImport(*command);
324 }
325
326 if (m_verbose)
327 m_log << "## Check semantic for " << context->sessions().size() << " sessions"
328 << std::endl;
329
330 // On vérifie chaque session
331 for (const auto session: context->sessions()) {
332 std::string sessionName = session->name();
333 O3prmrSession< double >* new_session = new O3prmrSession< double >(sessionName);
334
335 if (m_verbose)
336 m_log << "## Start session '" << sessionName << "'..." << std::endl << std::endl;
337
338 for (const auto command: session->commands()) {
339 if (m_verbose)
340 m_log << "# * Going to check command : " << command->toString() << std::endl;
341
342 // Update the current line (for warnings and errors)
343 m_current_line = command->line;
344
345 // We check it.
346 bool result = true;
347
348 try {
349 switch (command->type()) {
351 result = checkSetEngine((SetEngineCommand*)command);
352 break;
353
355 result = checkSetGndEngine((SetGndEngineCommand*)command);
356 break;
357
359 result = checkObserve((ObserveCommand< double >*)command);
360 break;
361
363 result = checkUnobserve((UnobserveCommand< double >*)command);
364 break;
365
367 result = checkQuery((QueryCommand< double >*)command);
368 break;
369
370 default :
371 addError("Error : Unknow command : " + command->toString()
372 + "\n -> Command not processed.");
373 result = false;
374 }
375 } catch (Exception& err) {
376 result = false;
377 addError(err.errorContent());
378 } catch (std::string& err) {
379 result = false;
380 addError(err);
381 }
382
383 // If there was a problem, skip the rest of this session,
384 // unless syntax mode is activated.
385 if (!result && !isInSyntaxMode()) {
386 if (m_verbose) m_log << "Errors : skip the rest of this session." << std::endl;
387
388 break;
389 }
390
391 // On l'ajoute au contexte globale
392 if (result) new_session->addCommand((const O3prmrCommand*)command);
393 }
394
395 // Ajoute la session au contexte global,
396 // ou à la dernière session.
397 if (sessionName == "default" && m_context->sessions().size() > 0)
398 *(m_context->sessions().back()) += *new_session;
399 else m_context->addSession(*new_session);
400
401 if (m_verbose)
402 m_log << std::endl
403 << "## Session '" << sessionName << "' finished." << std::endl
404 << std::endl
405 << std::endl;
406
407 // todo : check memory leak
408 // delete new_session; ??
409 }
410
411 if (isVerboseMode() && errors() != 0) m_errors.elegantErrorsAndWarnings(m_log);
412
413 return errors() == 0;
414 }
415
417 m_engine = command->value;
418 return m_engine == "SVED" || m_engine == "GRD" || m_engine == "SVE";
419 }
420
422 m_bn_engine = command->value;
423 return m_bn_engine == "VE" || m_bn_engine == "VEBB" || m_bn_engine == "lazy";
424 }
425
427 try {
428 std::string left_val = command->leftValue;
429 const std::string right_val = command->rightValue;
430
431 // Contruct the pair (instance,attribut)
432 const PRMSystem< double >& sys = system(left_val);
433 const PRMInstance< double >& instance = sys.get(findInstanceName(left_val, sys));
434 const PRMAttribute< double >& attr = instance.get(findAttributeName(left_val, instance));
435 typename PRMInference< double >::Chain chain = std::make_pair(&instance, &attr);
436
437 command->system = &sys;
438 command->chain = std::make_pair(&instance, &attr);
439
440 // Check label exists for this type.
441 // Tensor<double> e;
442 command->potentiel.add(chain.second->type().variable());
443 Instantiation i(command->potentiel);
444 bool found = false;
445
446 for (i.setFirst(); !i.end(); i.inc()) {
447 if (chain.second->type().variable().label(i.val(chain.second->type().variable()))
448 == right_val) {
449 command->potentiel.set(i, (double)1.0);
450 found = true;
451 } else {
452 command->potentiel.set(i, (double)0.0);
453 }
454 }
455
456 if (!found) addError(right_val + " is not a label of " + left_val);
457
458 // else command->potentiel = e;
459
460 return found;
461 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
462 addError(err);
463 }
464
465 return false;
466 }
467
469 try {
470 std::string name = command->value;
471
472 // Contruct the pair (instance,attribut)
473 const PRMSystem< double >& sys = system(name);
474 const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
475 const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
476 // PRMInference<double>::Chain chain = std::make_pair(&instance,
477 // &attr);
478
479 command->system = &sys;
480 command->chain = std::make_pair(&instance, &attr);
481
482 return true;
483 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
484 addError(err);
485 }
486
487 return false;
488 }
489
491 try {
492 std::string name = command->value;
493
494 // Contruct the pair (instance,attribut)
495 const PRMSystem< double >& sys = system(name);
496 const PRMInstance< double >& instance = sys.get(findInstanceName(name, sys));
497 const PRMAttribute< double >& attr = instance.get(findAttributeName(name, instance));
498 // PRMInference<double>::Chain chain = std::make_pair(&instance,
499 // &attr);
500
501 command->system = &sys;
502 command->chain = std::make_pair(&instance, &attr);
503
504 return true;
505 } catch (Exception& err) { addError(err.errorContent()); } catch (std::string& err) {
506 addError(err);
507 }
508
509 return false;
510 }
511
512 // Import the system o3prm file
513 // Return false if any error.
514
515 bool O3prmrInterpreter::import(O3prmrContext< double >* context, std::string import_name) {
516 try {
517 if (m_verbose) { m_log << "# Loading system '" << import_name << "' => '" << std::flush; }
518
519 std::string import_package = import_name;
520
521 std::replace(import_name.begin(), import_name.end(), '.', '/');
522 import_name += ".o3prm";
523
524 if (m_verbose) { m_log << import_name << "' ... " << std::endl << std::flush; }
525
526 std::ifstream file_test;
527 bool found = false;
528 std::string import_abs_filename;
529
530 // Search in o3prmr file dir.
531 std::string o3prmrFilename = context->filename();
532
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;
537
538 if (m_verbose) {
539 m_log << "# Search from filedir '" << import_abs_filename << "' ... " << std::flush;
540 }
541
542 file_test.open(import_abs_filename.c_str());
543
544 if (file_test.is_open()) {
545 if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
546
547 file_test.close();
548 found = true;
549 } else if (m_verbose) {
550 m_log << "not found." << std::endl << std::flush;
551 }
552 }
553 }
554
555 // Deduce root path from package name.
556 std::string package = context->package();
557
558 if (!found && !package.empty()) {
559 std::string root;
560
561 // if filename is not empty, start from it.
562 std::string filename = context->filename();
563
564 if (!filename.empty()) {
565 if (auto size = filename.find_last_of('/'); size != std::string::npos) {
566 root += filename.substr(0, size + 1); // take with the '/'
567 }
568 }
569
570 //
571 root += "../";
572 int count = (int)std::count(package.begin(), package.end(), '.');
573
574 for (int i = 0; i < count; i++)
575 root += "../";
576
577 import_abs_filename = std::filesystem::absolute(std::filesystem::path(root)
578 / std::filesystem::path(import_name))
579 .string();
580
581 if (m_verbose) {
582 m_log << "# Search from package '" << package << "' => '" << import_abs_filename
583 << "' ... " << std::flush;
584 }
585
586 file_test.open(import_abs_filename.c_str());
587
588 if (file_test.is_open()) {
589 if (m_verbose) { m_log << "found !" << std::endl << std::flush; }
590
591 file_test.close();
592 found = true;
593 } else if (m_verbose) {
594 m_log << "not found." << std::endl << std::flush;
595 }
596 }
597
598 // Search import in all paths.
599 for (const auto& path: m_paths) {
600 import_abs_filename = path + import_name;
601
602 if (m_verbose) {
603 m_log << "# Search from classpath '" << import_abs_filename << "' ... " << std::flush;
604 }
605
606 file_test.open(import_abs_filename.c_str());
607
608 if (file_test.is_open()) {
609 if (m_verbose) { m_log << " found !" << std::endl << std::flush; }
610
611 file_test.close();
612 found = true;
613 break;
614 } else if (m_verbose) {
615 m_log << " not found." << std::endl << std::flush;
616 }
617 }
618
619 if (!found) {
620 if (m_verbose) { m_log << "Finished with errors." << std::endl; }
621
622 addError("import not found.");
623 return false;
624 }
625
626 // May throw std::IOError if file does't exist
627 Size previousO3prmError = m_reader->errors();
628 Size previousO3prmrError = errors();
629
630 try {
631 m_reader->readFile(import_abs_filename, import_package);
632
633 // Show errors and warning
634 if (m_verbose
635 && (m_reader->errors() > (unsigned int)previousO3prmError
636 || errors() > previousO3prmrError)) {
637 m_log << "Finished with errors." << std::endl;
638 } else if (m_verbose) {
639 m_log << "Finished." << std::endl;
640 }
641 } catch (const IOError& err) {
642 if (m_verbose) { m_log << "Finished with errors." << std::endl; }
643
644 addError(err.errorContent());
645 }
646
647 // Add o3prm errors and warnings to o3prmr errors
648 for (; previousO3prmError < m_reader->errorsContainer().count(); previousO3prmError++) {
649 m_errors.add(m_reader->errorsContainer().error(previousO3prmError));
650 }
651
652 return errors() == previousO3prmrError;
653 } catch (const Exception& err) {
654 if (m_verbose) { m_log << "Finished with exceptions." << std::endl; }
655
656 addError(err.errorContent());
657 return false;
658 }
659 }
660
661 std::string O3prmrInterpreter::findSystemName(std::string& s) {
662 size_t dot = s.find_first_of('.');
663 std::string name = s.substr(0, dot);
664
665 // We look first for real system, next for alias.
666 if (prm()->isSystem(name)) {
667 s = s.substr(dot + 1);
668 return name;
669 }
670
671 if (!m_context->aliasToImport(name).empty()) {
672 s = s.substr(dot + 1);
673 return m_context->aliasToImport(name);
674 }
675
676 while (dot != std::string::npos) {
677 if (prm()->isSystem(name)) {
678 s = s.substr(dot + 1);
679 return name;
680 }
681
682 dot = s.find('.', dot + 1);
683 name = s.substr(0, dot);
684 }
685
686 throw "could not find any system in '" + s + "'.";
687 }
688
689 std::string O3prmrInterpreter::findInstanceName(std::string& s,
690 const PRMSystem< double >& sys) {
691 // We have found system before, so 's' has been stripped.
692 size_t dot = s.find_first_of('.');
693 std::string name = s.substr(0, dot);
694
695 if (!sys.exists(name))
696 throw "'" + name + "' is not an instance of system '" + sys.name() + "'.";
697
698 s = s.substr(dot + 1);
699 return name;
700 }
701
702 std::string O3prmrInterpreter::findAttributeName(std::string_view s,
703 const PRMInstance< double >& instance) {
704 if (!instance.exists(s))
705 throw "'" + std::string{s} + "' is not an attribute of instance '" + instance.name()
706 + "'.";
707
708 return std::string{s};
709 }
710
711 // After this method, ident doesn't contains the system name anymore.
713 try {
714 return prm()->getSystem(findSystemName(ident));
715 } catch (const std::string&) {}
716
717 if ((m_context->mainImport() != 0) && prm()->isSystem(m_context->mainImport()->value))
718 return prm()->getSystem(m_context->mainImport()->value);
719
720 throw "could not find any system or alias in '" + ident
721 + "' and no default alias has been set.";
722 }
723
725
727 const typename PRMInference< double >::Chain& chain = command->chain;
728
729 // Generate the inference engine if it doesn't exist.
730 if (!m_inf) { generateInfEngine(*(command->system)); }
731
732 // Prevent from something
733 if (m_inf->hasEvidence(chain)) addWarning(command->leftValue + " is already observed");
734
735 m_inf->addEvidence(chain, command->potentiel);
736
737 if (m_verbose)
738 m_log << "# Added evidence " << command->rightValue << " over attribute "
739 << command->leftValue << std::endl;
740
741 return true;
742 } catch (OperationNotAllowed& ex) {
743 addError("something went wrong when adding evidence " + command->rightValue + " over "
744 + command->leftValue + " : " + ex.errorContent());
745 return false;
746 } catch (const std::string& msg) {
747 addError(msg);
748 return false;
749 }
750
752
754 std::string name = command->value;
755 typename PRMInference< double >::Chain chain = command->chain;
756
757 // Prevent from something
758 if (!m_inf || !m_inf->hasEvidence(chain)) {
759 addWarning(name + " was not observed");
760 } else {
761 m_inf->removeEvidence(chain);
762
763 if (m_verbose) m_log << "# Removed evidence over attribute " << name << std::endl;
764 }
765
766 return true;
767 } catch (const std::string& msg) {
768 addError(msg);
769 return false;
770 }
771
774 const std::string& query = command->value;
775
776 if (m_inf_map.exists(command->system)) {
777 m_inf = m_inf_map[command->system];
778 } else {
779 m_inf = nullptr;
780 }
781
782 // Create inference engine if it has not been already created.
783 if (!m_inf) { generateInfEngine(*(command->system)); }
784
785 // Inference
786 if (m_verbose) {
787 m_log << "# Starting inference over query: " << query << "... " << std::endl;
788 }
789
790 Timer timer;
791 timer.reset();
792
794 m_inf->posterior(command->chain, m);
795
796 // Compute spent time
797 double t = timer.step();
798
799 if (m_verbose) { m_log << "Finished." << std::endl; }
800
801 if (m_verbose) { m_log << "# Time in seconds (accuracy ~0.001): " << t << std::endl; }
802
803 // Show results
804
805 if (m_verbose) { m_log << std::endl; }
806
807 QueryResult result;
808 result.command = query;
809 result.time = t;
810
811 Instantiation j(m);
812 const PRMAttribute< double >& attr = *(command->chain.second);
813
814 for (j.setFirst(); !j.end(); j.inc()) {
815 // auto label_value = j.val ( attr.type().variable() );
816 auto label_value = j.val(0);
817 std::string label = attr.type().variable().label(label_value);
818 float value = float(m.get(j));
819
820 SingleResult singleResult;
821 singleResult.label = label;
822 singleResult.p = value;
823
824 result.values.push_back(singleResult);
825
826 if (m_verbose) { m_log << label << " : " << value << std::endl; }
827 }
828
829 m_results.push_back(result);
830
831 if (m_verbose) { m_log << std::endl; }
832 } catch (Exception& e) {
833 GUM_SHOWERROR(e);
834 throw "something went wrong while infering: " + e.errorContent();
835 } catch (const std::string& msg) { addError(msg); }
836
839 m_engine = command->value;
840 }
841
844 m_bn_engine = command->value;
845 }
846
849 if (m_verbose) m_log << "# Building the inference engine... " << std::flush;
850
851 //
852 if (m_engine == "SVED") {
853 m_inf = new SVED< double >(*(prm()), sys);
854
855 //
856 } else if (m_engine == "SVE") {
857 m_inf = new SVE< double >(*(prm()), sys);
858 } else {
859 if (m_engine != "GRD") {
860 addWarning("unkown engine '" + m_engine + "', use GRD insteed.");
861 }
862
863 MarginalTargetedInference< double >* bn_inf = nullptr;
864 if (m_bn) { delete m_bn; }
865 m_bn = new BayesNet< double >();
867
868 if (m_verbose) m_log << "(Grounding the network... " << std::flush;
869
870 sys.groundedBN(bn_factory);
871
872 if (m_verbose) m_log << "Finished)" << std::flush;
873
874 // bn_inf = new LazyPropagation<double>( *m_bn );
876
877 auto grd_inf = new GroundedInference< double >(*(prm()), sys);
878 grd_inf->setBNInference(bn_inf);
879 m_inf = grd_inf;
880 }
881
882 m_inf_map.insert(&sys, m_inf);
883 if (m_verbose) m_log << "Finished." << std::endl;
884 }
885
886 /* **************************************************************************
887 */
888
890 Size O3prmrInterpreter::count() const { return m_errors.count(); }
891
893 Size O3prmrInterpreter::errors() const { return m_errors.error_count; }
894
896 Size O3prmrInterpreter::warnings() const { return m_errors.warning_count; }
897
900 if (i >= count()) throw "Index out of bound.";
901
902 return m_errors.error(i);
903 }
904
907
909 void O3prmrInterpreter::showElegantErrors(std::ostream& o) const {
910 m_errors.elegantErrors(o);
911 }
912
915 m_errors.elegantErrorsAndWarnings(o);
916 }
917
919 void O3prmrInterpreter::showErrorCounts(std::ostream& o) const {
920 m_errors.syntheticResults(o);
921 }
922
923 /* **************************************************************************
924 */
925
927 void O3prmrInterpreter::addError(std::string msg) {
928 m_errors.addError(msg, m_context->filename(), m_current_line, 0);
929
930 if (m_verbose) m_log << m_errors.last().toString() << std::endl;
931 }
932
934 void O3prmrInterpreter::addWarning(std::string msg) {
935 m_errors.addWarning(msg, m_context->filename(), m_current_line, 0);
936
937 if (m_verbose) m_log << m_errors.last().toString() << std::endl;
938 }
939 } // namespace o3prmr
940 } // namespace prm
941} // 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-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.
Definition exceptions.h:122
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.
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:53
double step() const
Returns the delta time between now and the last reset() call (or the constructor).
Definition timer_inl.h:72
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.
Definition PRMInstance.h:79
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.
Definition PRMType_inl.h:65
This class represents a Probabilistic Relational PRMSystem<GUM_SCALAR>.
Definition PRM.h:74
This class is an implementation of the Structured Value Elimination algorithm on PRM<GUM_SCALAR>.
Definition SVED.h:74
This class is an implementation of the Structured Variable Elimination algorithm on PRM<GUM_SCALAR>.
Definition SVE.h:74
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)
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
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)
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
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.
This class contains a o3prmr session.
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
std::string toString() const override
PRMInference< GUM_SCALAR >::Chain chain
const PRMSystem< GUM_SCALAR > * system
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
#define GUM_SHOWERROR(e)
Definition exceptions.h:89
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.