aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
O3ClassFactory_tpl.h
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#pragma once
42
43
51
54
55namespace gum {
56 namespace prm {
57 namespace o3prm {
58
59 template < GUM_Numeric GUM_SCALAR >
61 O3PRM& o3_prm,
63 ErrorsContainer& errors) :
64 _prm_(&prm), _o3_prm_(&o3_prm), _solver_(&solver), _errors_(&errors) {
65 GUM_CONSTRUCTOR(O3ClassFactory);
66 }
67
68 template < GUM_Numeric GUM_SCALAR >
75
76 template < GUM_Numeric GUM_SCALAR >
78 _prm_(std::move(src._prm_)), _o3_prm_(std::move(src._o3_prm_)),
79 _solver_(std::move(src._solver_)), _errors_(std::move(src._errors_)),
80 _nameMap_(std::move(src._nameMap_)), _classMap_(std::move(src._classMap_)),
81 _nodeMap_(std::move(src._nodeMap_)), _dag_(std::move(src._dag_)),
82 _o3Classes_(std::move(src._o3Classes_)) {
83 GUM_CONS_MOV(O3ClassFactory);
84 }
85
86 template < GUM_Numeric GUM_SCALAR >
90
91 template < GUM_Numeric GUM_SCALAR >
94 if (this == &src) { return *this; }
95 _prm_ = src._prm_;
96 _o3_prm_ = src._o3_prm_;
97 _solver_ = src._solver_;
98 _errors_ = src._errors_;
99 _nameMap_ = src._nameMap_;
101 _nodeMap_ = src._nodeMap_;
102 _dag_ = src._dag_;
104 return *this;
105 }
106
107 template < GUM_Numeric GUM_SCALAR >
110 if (this == &src) { return *this; }
111 _prm_ = std::move(src._prm_);
112 _o3_prm_ = std::move(src._o3_prm_);
113 _solver_ = std::move(src._solver_);
114 _errors_ = std::move(src._errors_);
115 _nameMap_ = std::move(src._nameMap_);
116 _classMap_ = std::move(src._classMap_);
117 _nodeMap_ = std::move(src._nodeMap_);
118 _dag_ = std::move(src._dag_);
119 _o3Classes_ = std::move(src._o3Classes_);
120 return *this;
121 }
122
123 template < GUM_Numeric GUM_SCALAR >
126
127 // Class with a super class must be declared after
128 if (_checkO3Classes_()) {
130
131 for (auto c: _o3Classes_) {
132 // Soving interfaces
133 auto implements = Set< std::string >();
134 for (auto& i: c->interfaces()) {
135 if (_solver_->resolveInterface(i)) { implements.insert(i.label()); }
136 }
137
138 // Adding the class
139 if (_solver_->resolveClass(c->superLabel())) {
140 factory.startClass(c->name().label(), c->superLabel().label(), &implements, true);
141 factory.endClass(false);
142 }
143 }
144 }
145 }
146
147 template < GUM_Numeric GUM_SCALAR >
149 auto topo_order = _dag_.topologicalOrder();
150
151 for (auto id = topo_order.rbegin(); id != topo_order.rend(); --id) {
152 _o3Classes_.push_back(_nodeMap_[*id]);
153 }
154 }
155
156 template < GUM_Numeric GUM_SCALAR >
160
161 template < GUM_Numeric GUM_SCALAR >
163 for (auto& c: _o3_prm_->classes()) {
164 auto id = _dag_.addNode();
165
166 try {
167 _nameMap_.insert(c->name().label(), id);
168 _classMap_.insert(c->name().label(), c.get());
169 _nodeMap_.insert(id, c.get());
170
171 } catch (DuplicateElement const&) {
172 O3PRM_CLASS_DUPLICATE(c->name(), *_errors_);
173 return false;
174 }
175 }
176
177 return true;
178 }
179
180 template < GUM_Numeric GUM_SCALAR >
182 for (auto& c: _o3_prm_->classes()) {
183 if (c->superLabel().label() != "") {
184 if (!_solver_->resolveClass(c->superLabel())) { return false; }
185
186 auto head = _nameMap_[c->superLabel().label()];
187 auto tail = _nameMap_[c->name().label()];
188
189 try {
190 _dag_.addArc(tail, head);
191 } catch (InvalidDirectedCycle const&) {
192 // Cyclic inheritance
193 O3PRM_CLASS_CYLIC_INHERITANCE(c->name(), c->superLabel(), *_errors_);
194 return false;
195 }
196 }
197 }
198
199 return true;
200 }
201
202 template < GUM_Numeric GUM_SCALAR >
204 for (auto& c: _o3_prm_->classes()) {
205 if (_checkImplementation_(*c)) {
206 _prm_->getClass(c->name().label()).initializeInheritance();
207 }
208 }
209 }
210
214
215 template < GUM_Numeric GUM_SCALAR >
217 // Saving attributes names for fast lookup
218 auto attr_map = AttrMap();
219 for (auto& a: c.attributes()) {
220 attr_map.insert(a->name().label(), a.get());
221 }
222
223 // Saving aggregates names for fast lookup
224 auto agg_map = AggMap();
225 for (auto& agg: c.aggregates()) {
226 agg_map.insert(agg.name().label(), &agg);
227 }
228
229 auto ref_map = RefMap();
230 for (auto& ref: c.referenceSlots()) {
231 ref_map.insert(ref.name().label(), &ref);
232 }
233
234 // Cheking interface implementation
235 for (auto& i: c.interfaces()) {
236 if (_solver_->resolveInterface(i)) {
237 if (!_checkImplementation_(c, i, attr_map, agg_map, ref_map)) { return false; }
238 }
239 }
240
241 return true;
242 }
243
244 template < GUM_Numeric GUM_SCALAR >
246 O3Label& i,
247 AttrMap& attr_map,
248 AggMap& agg_map,
249 RefMap& ref_map) {
250 const auto& real_i = _prm_->getInterface(i.label());
251
252 auto counter = (Size)0;
253 for (const auto& a: real_i.attributes()) {
254 if (attr_map.exists(a->name())) {
255 ++counter;
256
257 if (!_checkImplementation_(attr_map[a->name()]->type(), a->type())) {
258 O3PRM_CLASS_ATTR_IMPLEMENTATION(c.name(), i, attr_map[a->name()]->name(), *_errors_);
259 return false;
260 }
261 }
262
263 if (agg_map.exists(a->name())) {
264 ++counter;
265
266 if (!_checkImplementation_(agg_map[a->name()]->variableType(), a->type())) {
267 O3PRM_CLASS_AGG_IMPLEMENTATION(c.name(), i, agg_map[a->name()]->name(), *_errors_);
268 return false;
269 }
270 }
271 }
272
273 if (counter != real_i.attributes().size()) {
274 O3PRM_CLASS_MISSING_ATTRIBUTES(c.name(), i, *_errors_);
275 return false;
276 }
277
278 counter = 0;
279 for (const auto& r: real_i.referenceSlots()) {
280 if (ref_map.exists(r->name())) {
281 ++counter;
282
283 if (!_checkImplementation_(ref_map[r->name()]->type(), r->slotType())) {
284 O3PRM_CLASS_REF_IMPLEMENTATION(c.name(), i, ref_map[r->name()]->name(), *_errors_);
285 return false;
286 }
287 }
288 }
289 return true;
290 }
291
292 template < GUM_Numeric GUM_SCALAR >
294 const PRMType& type) {
295 if (!_solver_->resolveType(o3_type)) { return false; }
296
297 return _prm_->type(o3_type.label()).isSubTypeOf(type);
298 }
299
300 template < GUM_Numeric GUM_SCALAR >
302 O3Label& o3_type,
304 if (!_solver_->resolveSlotType(o3_type)) { return false; }
305
306 if (_prm_->isInterface(o3_type.label())) {
307 return _prm_->getInterface(o3_type.label()).isSubTypeOf(type);
308 } else {
309 return _prm_->getClass(o3_type.label()).isSubTypeOf(type);
310 }
311 }
312
313 template < GUM_Numeric GUM_SCALAR >
316 // Class with a super class must be declared after
317 for (auto c: _o3Classes_) {
318 _prm_->getClass(c->name().label()).inheritParameters();
319
320 factory.continueClass(c->name().label());
321
322 _addParameters_(factory, *c);
323
324 factory.endClass(false);
325 }
326 }
327
328 template < GUM_Numeric GUM_SCALAR >
330 O3Class& c) {
331 for (auto& p: c.parameters()) {
332 switch (p.type()) {
334 factory.addParameter("int", p.name().label(), p.value().value());
335 break;
336 }
337
339 factory.addParameter("real", p.name().label(), p.value().value());
340 break;
341 }
342
343 default : {
344 GUM_ERROR(FatalError, "unknown O3Parameter type")
345 }
346 }
347 }
348 }
349
350 template < GUM_Numeric GUM_SCALAR >
352 // Class with a super class must be declared after
353 for (auto c: _o3Classes_) {
354 _prm_->getClass(c->name().label()).inheritReferenceSlots();
356 }
357 }
358
359 template < GUM_Numeric GUM_SCALAR >
362
363 factory.continueClass(c.name().label());
364
365 // References
366 for (auto& ref: c.referenceSlots()) {
367 if (_checkReferenceSlot_(c, ref)) {
368 factory.addReferenceSlot(ref.type().label(), ref.name().label(), ref.isArray());
369 }
370 }
371
372 factory.endClass(false);
373 }
374
375 template < GUM_Numeric GUM_SCALAR >
377 if (!_solver_->resolveSlotType(ref.type())) { return false; }
378
379 const auto& real_c = _prm_->getClass(c.name().label());
380
381 // Check for dupplicates
382 if (real_c.exists(ref.name().label())) {
383 const auto& elt = real_c.get(ref.name().label());
384
386 auto slot_type = (PRMClassElementContainer< GUM_SCALAR >*)nullptr;
387
388 if (_prm_->isInterface(ref.type().label())) {
389 slot_type = &(_prm_->getInterface(ref.type().label()));
390
391 } else {
392 slot_type = &(_prm_->getClass(ref.type().label()));
393 }
394
395 auto real_ref = static_cast< const PRMReferenceSlot< GUM_SCALAR >* >(&elt);
396
397 if (slot_type->name() == real_ref->slotType().name()) {
398 O3PRM_CLASS_DUPLICATE_REFERENCE(ref.name(), *_errors_);
399 return false;
400
401 } else if (!slot_type->isSubTypeOf(real_ref->slotType())) {
402 O3PRM_CLASS_ILLEGAL_OVERLOAD(ref.name(), c.name(), *_errors_);
403 return false;
404 }
405
406 } else {
407 O3PRM_CLASS_DUPLICATE_REFERENCE(ref.name(), *_errors_);
408 return false;
409 }
410 }
411
412 // If class we need to check for illegal references
413 if (_prm_->isClass(ref.type().label())) {
414 const auto& ref_type = _prm_->getClass(ref.type().label());
415
416 // No recursive reference
417 if ((&ref_type) == (&real_c)) {
418 O3PRM_CLASS_SELF_REFERENCE(c.name(), ref.name(), *_errors_);
419 return false;
420 }
421
422 // No reference to subclasses
423 if (ref_type.isSubTypeOf(real_c)) {
424 O3PRM_CLASS_ILLEGAL_SUB_REFERENCE(c.name(), ref.type(), *_errors_);
425 return false;
426 }
427 }
428
429 return true;
430 }
431
432 template < GUM_Numeric GUM_SCALAR >
434 // Class with a super class must be declared after
435 for (auto c: _o3Classes_) {
436 _prm_->getClass(c->name().label()).inheritAttributes();
438 }
439 }
440
441 template < GUM_Numeric GUM_SCALAR >
443 // Class with a super class must be declared after
444 for (auto c: _o3Classes_) {
445 _prm_->getClass(c->name().label()).inheritAggregates();
447 }
448 }
449
450 template < GUM_Numeric GUM_SCALAR >
453 factory.continueClass(c.name().label());
454
455 for (auto& attr: c.attributes()) {
456 if (_checkAttributeForDeclaration_(c, *attr)) {
457 factory.startAttribute(attr->type().label(), attr->name().label());
458 factory.endAttribute();
459 }
460 }
461
462 factory.endClass(false);
463 }
464
465 template < GUM_Numeric GUM_SCALAR >
467 O3Attribute& attr) {
468 // Check type
469 if (!_solver_->resolveType(attr.type())) { return false; }
470
471 // Checking type legality if overload
472 if (c.superLabel().label() != "") {
473 const auto& super = _prm_->getClass(c.superLabel().label());
474
475 if (!super.exists(attr.name().label())) { return true; }
476
477 const auto& super_type = super.get(attr.name().label()).type();
478 const auto& type = _prm_->type(attr.type().label());
479
480 if (!type.isSubTypeOf(super_type)) {
481 O3PRM_CLASS_ILLEGAL_OVERLOAD(attr.name(), c.superLabel(), *_errors_);
482 return false;
483 }
484 }
485 return true;
486 }
487
488 template < GUM_Numeric GUM_SCALAR >
491
492 // Class with a super class must be declared in order
493 for (auto c: _o3Classes_) {
494 _prm_->getClass(c->name().label()).inheritSlotChains();
495 factory.continueClass(c->name().label());
496
497 _completeAttribute_(factory, *c);
498
499 if (c->superLabel().label() != "") {
500 auto& super = _prm_->getClass(c->superLabel().label());
501 auto to_complete = Set< std::string >();
502
503 for (auto a: super.attributes()) {
504 to_complete.insert(a->safeName());
505 }
506
507 for (auto a: super.aggregates()) {
508 to_complete.insert(a->safeName());
509 }
510
511 for (auto& a: c->attributes()) {
512 to_complete.erase(
513 _prm_->getClass(c->name().label()).get(a->name().label()).safeName());
514 }
515
516 for (auto& a: c->aggregates()) {
517 to_complete.erase(
518 _prm_->getClass(c->name().label()).get(a.name().label()).safeName());
519 }
520
521 for (auto a: to_complete) {
522 _prm_->getClass(c->name().label()).completeInheritance(a);
523 }
524 }
525
526 factory.endClass(true);
527 }
528 }
529
530 template < GUM_Numeric GUM_SCALAR >
533
534 // Class with a super class must be declared in order
535 for (auto c: _o3Classes_) {
536 factory.continueClass(c->name().label());
537
538 _completeAggregates_(factory, *c);
539
540 factory.endClass(false);
541 }
542 }
543
544 template < GUM_Numeric GUM_SCALAR >
546 O3Class& c) {
547 // Attributes
548 for (auto& agg: c.aggregates()) {
549 if (_checkAggregateForCompletion_(c, agg)) {
550 factory.continueAggregator(agg.name().label());
551
552 for (const auto& parent: agg.parents()) {
553 factory.addParent(parent.label());
554 }
555
556 factory.endAggregator();
557 }
558 }
559 }
560
561 template < GUM_Numeric GUM_SCALAR >
563 O3Aggregate& agg) {
564 // Checking parents
565 auto t = _checkAggParents_(c, agg);
566 if (t == nullptr) { return false; }
567
568 // Checking parameters numbers
569 if (!_checkAggParameters_(c, agg, t)) { return false; }
570
571 return true;
572 }
573
574 template < GUM_Numeric GUM_SCALAR >
576 O3Class& c) {
577 // Attributes
578 for (auto& attr: c.attributes()) {
579 if (_checkAttributeForCompletion_(c, *attr)) {
580 factory.continueAttribute(attr->name().label());
581
582 for (const auto& parent: attr->parents()) {
583 factory.addParent(parent.label());
584 }
585
586 if (auto raw = dynamic_cast< const O3RawCPT* >(attr.get())) {
587 auto values = std::vector< std::string >();
588 for (const auto& val: raw->values()) {
589 values.push_back(val.formula().formula());
590 }
591 factory.setRawCPFByColumns(values);
592 }
593
594 if (auto rule_cpt = dynamic_cast< const O3RuleCPT* >(attr.get())) {
595 for (const auto& rule: rule_cpt->rules()) {
596 auto labels = std::vector< std::string >();
597 auto values = std::vector< std::string >();
598
599 for (const auto& lbl: rule.first) {
600 labels.push_back(lbl.label());
601 }
602
603 for (const auto& form: rule.second) {
604 values.push_back(form.formula().formula());
605 }
606
607 factory.setCPFByRule(labels, values);
608 }
609 }
610
611 factory.endAttribute();
612 }
613 }
614 }
615
616 template < GUM_Numeric GUM_SCALAR >
618 O3Attribute& attr) {
619 // Check for parents existence
620 const auto& c = _prm_->getClass(o3_c.name().label());
621 for (auto& prnt: attr.parents()) {
622 if (!_checkParent_(c, prnt)) { return false; }
623 }
624
625 // Check that CPT sums to 1
626 if (auto raw = dynamic_cast< O3RawCPT* >(&attr)) { return _checkRawCPT_(c, *raw); }
627
628 if (auto rule = dynamic_cast< O3RuleCPT* >(&attr)) { return _checkRuleCPT_(c, *rule); }
629
630 return true;
631 }
632
633 template < GUM_Numeric GUM_SCALAR >
635 const O3Label& prnt) {
636 if (prnt.label().find('.') == std::string::npos) {
637 return _checkLocalParent_(c, prnt);
638
639 } else {
640 return _checkRemoteParent_(c, prnt);
641 }
642 }
643
644 template < GUM_Numeric GUM_SCALAR >
646 const O3Label& prnt) {
647 if (!c.exists(prnt.label())) {
648 O3PRM_CLASS_PARENT_NOT_FOUND(prnt, *_errors_);
649 return false;
650 }
651
652 const auto& elt = c.get(prnt.label());
656 O3PRM_CLASS_ILLEGAL_PARENT(prnt, *_errors_);
657 return false;
658 }
659
660 return true;
661 }
662
663 template < GUM_Numeric GUM_SCALAR >
666 const O3Label& prnt) {
667 if (_resolveSlotChain_(c, prnt) == nullptr) { return false; }
668 return true;
669 }
670
671 template < GUM_Numeric GUM_SCALAR >
673 const O3RuleCPT::O3Rule& rule) {
674 // Check that the number of labels is correct
675 if (rule.first.size() != attr.parents().size()) {
676 O3PRM_CLASS_ILLEGAL_RULE_SIZE(rule, rule.first.size(), attr.parents().size(), *_errors_);
677 return false;
678 }
679 return true;
680 }
681
682 template < GUM_Numeric GUM_SCALAR >
684 const O3RuleCPT& attr,
685 const O3RuleCPT::O3Rule& rule) {
686 bool errors = false;
687 for (std::size_t i = 0; i < attr.parents().size(); ++i) {
688 auto label = rule.first[i];
689 auto prnt = attr.parents()[i];
690 try {
691 auto real_labels = _resolveSlotChain_(c, prnt)->type()->labels();
692 // c.get(prnt.label()).type()->labels();
693 if (label.label() != "*"
694 && std::find(real_labels.begin(), real_labels.end(), label.label())
695 == real_labels.end()) {
696 O3PRM_CLASS_ILLEGAL_RULE_LABEL(rule, label, prnt, *_errors_);
697 errors = true;
698 }
699 } catch (Exception const&) {
700 // parent does not exists and is already reported
701 }
702 }
703 return errors == false;
704 }
705
706 template < GUM_Numeric GUM_SCALAR >
708 const HashTable< std::string, const PRMParameter< GUM_SCALAR >* >& scope,
709 O3RuleCPT::O3Rule& rule) {
710 // Add parameters to formulas
711 for (auto& f: rule.second) {
712 f.formula().variables().clear();
713 for (const auto& values: scope) {
714 f.formula().variables().insert(values.first, values.second->value());
715 }
716 }
717 }
718
719 template < GUM_Numeric GUM_SCALAR >
721 const O3RuleCPT& attr,
722 const O3RuleCPT::O3Rule& rule) {
723 bool errors = false;
724 // Check that formulas are valid and sums to 1
725 GUM_SCALAR sum = 0.0;
726 for (const auto& f: rule.second) {
727 try {
728 auto value = GUM_SCALAR(f.formula().result());
729 sum += value;
730 if (value < 0.0 || 1.0 < value) {
731 O3PRM_CLASS_ILLEGAL_CPT_VALUE(c.name(), attr.name(), f, *_errors_);
732 errors = true;
733 }
734 } catch (OperationNotAllowed const&) {
735 O3PRM_CLASS_ILLEGAL_CPT_VALUE(c.name(), attr.name(), f, *_errors_);
736 errors = true;
737 }
738 }
739
740 // Check that CPT sums to 1
741 if (std::abs(sum - 1.0) > config().epsilonCoarse()) {
742 O3PRM_CLASS_CPT_DOES_NOT_SUM_TO_1(c.name(), attr.name(), float(sum), *_errors_);
743 errors = true;
744 } else if (std::abs(sum - 1.0f) > config().epsilonStandard()) {
745 O3PRM_CLASS_CPT_DOES_NOT_SUM_TO_1_WARNING(c.name(), attr.name(), float(sum), *_errors_);
746 }
747 return errors == false;
748 }
749
750 template < GUM_Numeric GUM_SCALAR >
752 O3RuleCPT& attr) {
753 const auto& scope = c.scope();
754 bool errors = false;
755 for (auto& rule: attr.rules()) {
756 try {
757 if (!_checkLabelsNumber_(attr, rule)) { errors = true; }
758 if (!_checkLabelsValues_(c, attr, rule)) { errors = true; }
759 _addParamsToForms_(scope, rule);
760 if (!_checkRuleCPTSumsTo1_(c, attr, rule)) { errors = true; }
761 } catch (Exception& e) {
762 GUM_SHOWERROR(e);
763 errors = true;
764 }
765 }
766
767 return errors == false;
768 }
769
770 template < GUM_Numeric GUM_SCALAR >
772 O3RawCPT& attr) {
773 const auto& type = _prm_->type(attr.type().label());
774
775 auto domainSize = type->domainSize();
776 for (auto& prnt: attr.parents()) {
777 if (c.exists(prnt.label())) {
778 domainSize *= c.get(prnt.label()).type()->domainSize();
779 } else {
780 // If we are here, all parents have been check so _resolveSlotChain_
781 // will not raise an error and not return a nullptr
782 domainSize *= _resolveSlotChain_(c, prnt)->type()->domainSize();
783 }
784 }
785
786 // Check for CPT size
787 if (domainSize != attr.values().size()) {
788 O3PRM_CLASS_ILLEGAL_CPT_SIZE(c.name(),
789 attr.name(),
790 Size(attr.values().size()),
791 domainSize,
792 *_errors_);
793 return false;
794 }
795
796 // Add parameters to formulas
797 const auto& scope = c.scope();
798 for (auto& f: attr.values()) {
799 f.formula().variables().clear();
800
801 for (const auto& values: scope) {
802 f.formula().variables().insert(values.first, values.second->value());
803 }
804 }
805
806 // Check that CPT sums to 1
807 Size parent_size = domainSize / type->domainSize();
808 auto values = std::vector< GUM_SCALAR >(parent_size, 0.0f);
809
810 for (std::size_t i = 0; i < attr.values().size(); ++i) {
811 try {
812 auto idx = i % parent_size;
813 auto val = (GUM_SCALAR)attr.values()[i].formula().result();
814 values[idx] += val;
815
816 if (val < 0.0 || 1.0 < val) {
817 O3PRM_CLASS_ILLEGAL_CPT_VALUE(c.name(), attr.name(), attr.values()[i], *_errors_);
818 return false;
819 }
820 } catch (Exception const&) {
821 O3PRM_CLASS_ILLEGAL_CPT_VALUE(c.name(), attr.name(), attr.values()[i], *_errors_);
822 return false;
823 }
824 }
825
826 for (auto f: values) {
827 if (std::abs(f - GUM_SCALAR(1.0)) > config().epsilonCoarse()) {
828 O3PRM_CLASS_CPT_DOES_NOT_SUM_TO_1(c.name(), attr.name(), float(f), *_errors_);
829 return false;
830 } else if (std::abs(f - GUM_SCALAR(1.0)) > config().epsilonStandard()) {
831 O3PRM_CLASS_CPT_DOES_NOT_SUM_TO_1_WARNING(c.name(), attr.name(), float(f), *_errors_);
832 }
833 }
834 return true;
835 }
836
837 template < GUM_Numeric GUM_SCALAR >
840 const O3Label& chain) {
841 auto s = chain.label();
842 auto current = &c;
843 std::vector< std::string > v;
844
845 decomposePath(chain.label(), v);
846
847 for (size_t i = 0; i < v.size(); ++i) {
848 auto link = v[i];
849
850 if (!_checkSlotChainLink_(*current, chain, link)) { return nullptr; }
851
852 auto elt = &(current->get(link));
853
854 if (i == v.size() - 1) {
855 // last link, should be an attribute or aggregate
856 return elt;
857
858 } else {
859 // should be a reference slot
860
861 if (auto ref = dynamic_cast< const PRMReferenceSlot< GUM_SCALAR >* >(elt)) {
862 current = &(ref->slotType());
863 } else {
864 return nullptr; // failsafe to prevent infinite loop
865 }
866 }
867 }
868
869 // Encountered only reference slots
870
871 return nullptr;
872 }
873
874 template < GUM_Numeric GUM_SCALAR >
877 const O3Label& chain,
878 std::string_view s) {
879 if (!c.exists(s)) {
880 O3PRM_CLASS_LINK_NOT_FOUND(chain, s, *_errors_);
881 return false;
882 }
883 return true;
884 }
885
886 template < GUM_Numeric GUM_SCALAR >
889 factory.continueClass(c.name().label());
890
891 for (auto& agg: c.aggregates()) {
892 if (_checkAggregateForDeclaration_(c, agg)) {
893 auto params = std::vector< std::string >();
894 for (auto& p: agg.parameters()) {
895 params.push_back(p.label());
896 }
897
898 factory.startAggregator(agg.name().label(),
899 agg.aggregateType().label(),
900 agg.variableType().label(),
901 params);
902 factory.endAggregator();
903 }
904 }
905
906 factory.endClass(false);
907 }
908
909 template < GUM_Numeric GUM_SCALAR >
911 O3Aggregate& agg) {
912 if (!_solver_->resolveType(agg.variableType())) { return false; }
913
914 // Checking type legality if overload
915 if (!_checkAggTypeLegality_(o3class, agg)) { return false; }
916
917 return true;
918 }
919
920 template < GUM_Numeric GUM_SCALAR >
922 O3Aggregate& agg) {
923 const auto& c = _prm_->getClass(o3class.name().label());
924 auto t = (const PRMType*)nullptr;
925
926 for (const auto& prnt: agg.parents()) {
927 auto elt = _resolveSlotChain_(c, prnt);
928
929 if (elt == nullptr) {
930 O3PRM_CLASS_PARENT_NOT_FOUND(prnt, *_errors_);
931 return nullptr;
932
933 } else {
934 if (t == nullptr) {
935 try {
936 t = &(elt->type());
937
938 } catch (OperationNotAllowed const&) {
939 O3PRM_CLASS_WRONG_PARENT(prnt, *_errors_);
940 return nullptr;
941 }
942
943 } else if ((*t) != elt->type()) {
944 // Wront type in chain
945 O3PRM_CLASS_WRONG_PARENT_TYPE(prnt, t->name(), elt->type().name(), *_errors_);
946 return nullptr;
947 }
948 }
949 }
950 return t;
951 }
952
953 template < GUM_Numeric GUM_SCALAR >
955 O3Aggregate& agg) {
956 if (_prm_->isClass(o3class.superLabel().label())) {
957 const auto& super = _prm_->getClass(o3class.superLabel().label());
958 const auto& agg_type = _prm_->type(agg.variableType().label());
959
960 if (super.exists(agg.name().label())
961 && !agg_type.isSubTypeOf(super.get(agg.name().label()).type())) {
962 O3PRM_CLASS_ILLEGAL_OVERLOAD(agg.name(), o3class.superLabel(), *_errors_);
963 return false;
964 }
965 }
966
967 return true;
968 }
969
970 template < GUM_Numeric GUM_SCALAR >
972 O3Aggregate& agg,
973 const PRMType* t) {
974 bool ok = false;
975
984 ok = _checkParametersNumber_(agg, 0);
985 break;
986 }
987
991 ok = _checkParametersNumber_(agg, 1);
992 break;
993 }
994
995 default : {
996 GUM_ERROR(FatalError, "unknown aggregate type")
997 }
998 }
999
1000 if (!ok) { return false; }
1001
1002 // Checking parameters type
1007 ok = _checkParameterValue_(agg, *t);
1008 break;
1009 }
1010
1011 default : { /* Nothing to do */
1012 }
1013 }
1014
1015 return ok;
1016 }
1017
1018 template < GUM_Numeric GUM_SCALAR >
1020 if (agg.parameters().size() != n) {
1021 O3PRM_CLASS_AGG_PARAMETERS(agg.name(), Size(n), Size(agg.parameters().size()), *_errors_);
1022 return false;
1023 }
1024
1025 return true;
1026 }
1027
1028 template < GUM_Numeric GUM_SCALAR >
1030 const gum::prm::PRMType& t) {
1031 const auto& param = agg.parameters().front();
1032 bool found = false;
1033 for (Size idx = 0; idx < t.variable().domainSize(); ++idx) {
1034 if (t.variable().label(idx) == param.label()) {
1035 found = true;
1036 break;
1037 }
1038 }
1039
1040 if (!found) {
1041 O3PRM_CLASS_AGG_PARAMETER_NOT_FOUND(agg.name(), param, *_errors_);
1042 return false;
1043 }
1044
1045 return true;
1046 }
1047
1048 } // namespace o3prm
1049 } // namespace prm
1050} // namespace gum
Headers for the O3ClassFactory class.
virtual std::string label(Idx i) const =0
get the indice-th label. This method is pure virtual.
Exception : a similar element already exists.
This class is used contain and manipulate gum::ParseError.
Base class for all aGrUM's exceptions.
Definition exceptions.h:133
Exception : fatal (unknown ?) error.
The class for generic Hash Tables.
Definition hashTable.h:640
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
Exception : existence of a directed cycle in a graph.
Exception : operation not allowed.
static AggregateType str2enum(std::string_view str)
Static method which returns the AggregateType given its string representation.
<agrum/PRM/classElementContainer.h>
virtual bool exists(std::string_view name) const
Returns true if a member with the given name exists in this PRMClassElementContainer or in the PRMCla...
Abstract class representing an element of PRM class.
static INLINE bool isAggregate(const PRMClassElement< GUM_SCALAR > &elt)
Return true if obj is of type PRMAggregate.
static INLINE bool isReferenceSlot(const PRMClassElement< GUM_SCALAR > &elt)
Returns true if obj_ptr is of type PRMReferenceSlot.
static INLINE bool isAttribute(const PRMClassElement< GUM_SCALAR > &elt)
Returns true if obj_ptr is of type PRMAttribute.
static INLINE bool isSlotChain(const PRMClassElement< GUM_SCALAR > &elt)
Return true if obj is of type PRMSlotChain.
A PRMClass is an object of a PRM representing a fragment of a Bayesian network which can be instantia...
Definition PRMClass.h:77
PRMClassElement< GUM_SCALAR > & get(NodeId id) override
See gum::prm::PRMClassElementContainer<GUM_SCALAR>::get(NodeId).
HashTable< std::string, const PRMParameter< GUM_SCALAR > * > scope() const
Returns all the parameters in the scope of this class.
Factory which builds a PRM<GUM_SCALAR>.
Definition PRMFactory.h:90
void addReferenceSlot(std::string_view type, std::string_view name, bool isArray) override
Tells the factory that we started declaring a slot.
void endAggregator()
Finishes an aggregate declaration.
void setRawCPFByColumns(const std::vector< GUM_SCALAR > &array)
Gives the factory the CPF in its raw form.
void continueAttribute(std::string_view name) override
Continues the declaration of an attribute.
virtual void setCPFByRule(const std::vector< std::string > &labels, const std::vector< GUM_SCALAR > &values)
Fills the CPF using a rule.
void startAttribute(std::string_view type, std::string_view name, bool scalar_atttr=false) override
Tells the factory that we start an attribute declaration.
void endClass(bool checkImplementations=true) override
Tells the factory that we finished a class declaration.
void continueAggregator(std::string_view name)
Conitnues an aggregator declaration.
void addParameter(std::string_view type, std::string_view name, double value) override
Add a parameter to the current class with a default value.
void startClass(std::string_view c, std::string_view ext="", const Set< std::string > *implements=nullptr, bool delayInheritance=false) override
Tells the factory that we start a class declaration.
void endAttribute() override
Tells the factory that we finished declaring an attribute.
void startAggregator(std::string_view name, std::string_view agg_type, std::string_view rv_type, const std::vector< std::string > &params)
Start an aggregator declaration.
void addParent(std::string_view name) override
Tells the factory that we add a parent to the current declared attribute.
void continueClass(std::string_view c) override
Continue the declaration of a class.
const std::string & name() const
Returns the name of this object.
PRMParameter is a member of a Class in a PRM.
A PRMReferenceSlot represent a relation between two PRMClassElementContainer.
This is a decoration of the DiscreteVariable class.
Definition PRMType.h:78
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
The O3Aggregate is part of the AST of the O3PRM language.
Definition O3prm.h:600
O3LabelList & parameters()
Definition O3prm.cpp:1162
O3LabelList & parents()
Definition O3prm.cpp:1158
The O3Attribute is part of the AST of the O3PRM language.
Definition O3prm.h:488
virtual O3Label & type()
Definition O3prm.cpp:743
virtual O3Label & name()
Definition O3prm.cpp:747
virtual O3LabelList & parents()
Definition O3prm.cpp:751
Builds gum::prm::Class from gum::prm::o3prm::O3Class.
bool _checkParent_(const PRMClass< GUM_SCALAR > &c, const O3Label &prnt)
O3NameSolver< GUM_SCALAR > * _solver_
bool _checkLabelsValues_(const PRMClass< GUM_SCALAR > &c, const O3RuleCPT &attr, const O3RuleCPT::O3Rule &rule)
void _addParamsToForms_(const HashTable< std::string, const PRMParameter< GUM_SCALAR > * > &scope, O3RuleCPT::O3Rule &rule)
O3ClassFactory(PRM< GUM_SCALAR > &prm, O3PRM &o3_prm, O3NameSolver< GUM_SCALAR > &solver, ErrorsContainer &errors)
HashTable< std::string, gum::NodeId > _nameMap_
bool _checkAggTypeLegality_(O3Class &o3class, O3Aggregate &agg)
void _completeAggregates_(PRMFactory< GUM_SCALAR > &factory, O3Class &c)
bool _checkLocalParent_(const PRMClass< GUM_SCALAR > &c, const O3Label &prnt)
std::vector< O3Class * > _o3Classes_
const PRMClassElement< GUM_SCALAR > * _resolveSlotChain_(const PRMClassElementContainer< GUM_SCALAR > &c, const O3Label &chain)
bool _checkAggParameters_(O3Class &o3class, O3Aggregate &agg, const PRMType *t)
bool _checkLabelsNumber_(const O3RuleCPT &attr, const O3RuleCPT::O3Rule &rule)
const PRMType * _checkAggParents_(O3Class &o3class, O3Aggregate &agg)
bool _checkParameterValue_(O3Aggregate &agg, const gum::prm::PRMType &t)
bool _checkAttributeForCompletion_(const O3Class &o3_c, O3Attribute &attr)
bool _checkAttributeForDeclaration_(O3Class &o3_c, O3Attribute &attr)
O3ClassFactory< GUM_SCALAR > & operator=(const O3ClassFactory< GUM_SCALAR > &src)
bool _checkAggregateForCompletion_(O3Class &o3class, O3Aggregate &agg)
bool _checkRemoteParent_(const PRMClassElementContainer< GUM_SCALAR > &c, const O3Label &prnt)
void _completeAttribute_(PRMFactory< GUM_SCALAR > &factory, O3Class &c)
bool _checkRuleCPT_(const PRMClass< GUM_SCALAR > &c, O3RuleCPT &attr)
void _addParameters_(PRMFactory< GUM_SCALAR > &factory, O3Class &c)
bool _checkParametersNumber_(O3Aggregate &agg, Size n)
HashTable< std::string, O3Class * > _classMap_
HashTable< NodeId, O3Class * > _nodeMap_
bool _checkReferenceSlot_(O3Class &c, O3ReferenceSlot &ref)
bool _checkRawCPT_(const PRMClass< GUM_SCALAR > &c, O3RawCPT &attr)
bool _checkRuleCPTSumsTo1_(const PRMClass< GUM_SCALAR > &c, const O3RuleCPT &attr, const O3RuleCPT::O3Rule &rule)
bool _checkAggregateForDeclaration_(O3Class &o3class, O3Aggregate &agg)
bool _checkSlotChainLink_(const PRMClassElementContainer< GUM_SCALAR > &c, const O3Label &chain, std::string_view s)
The O3Class is part of the AST of the O3PRM language.
Definition O3prm.h:642
O3ParameterList & parameters()
Definition O3prm.cpp:970
O3AggregateList & aggregates()
Definition O3prm.cpp:980
O3LabelList & interfaces()
Definition O3prm.cpp:966
O3ReferenceSlotList & referenceSlots()
Definition O3prm.cpp:974
O3Label & superLabel()
Definition O3prm.cpp:962
O3AttributeList & attributes()
Definition O3prm.cpp:976
The O3Label is part of the AST of the O3PRM language.
Definition O3prm.h:194
std::string & label()
Definition O3prm.cpp:286
Resolves names for the different O3PRM factories.
The O3PRM is part of the AST of the O3PRM language.
Definition O3prm.h:915
The O3RawCPT is part of the AST of the O3PRM language.
Definition O3prm.h:525
virtual O3FormulaList & values()
Definition O3prm.cpp:798
The O3ReferenceSlot is part of the AST of the O3PRM language.
Definition O3prm.h:455
The O3RuleCPT is part of the AST of the O3PRM language.
Definition O3prm.h:561
std::pair< O3LabelList, O3FormulaList > O3Rule
Definition O3prm.h:565
virtual O3RuleList & rules()
Definition O3prm.cpp:850
Typed, documented, sectioned configuration singleton read from an .ini content.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
#define GUM_SHOWERROR(e)
Definition exceptions.h:89
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
HashTable< std::string, O3Aggregate * > AggMap
HashTable< std::string, O3ReferenceSlot * > RefMap
HashTable< std::string, O3Attribute * > AttrMap
namespace for all probabilistic relational models entities
Definition agrum.h:68
void decomposePath(std::string_view path, std::vector< std::string > &v)
Decompose a string in a vector of strings using "." as separators.
Definition utils_prm.cpp:48
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
STL namespace.