56 template < GUM_Numeric GUM_SCALAR >
67 template < GUM_Numeric GUM_SCALAR >
75 if (a != b || a != c )
77 "addVariable : not the same id over all networks : " << a <<
", " << b <<
", "
83 template < GUM_Numeric GUM_SCALAR >
90 template < GUM_Numeric GUM_SCALAR >
93 const std::vector< std::vector< std::vector< GUM_SCALAR > > >& cpt) {
94 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(
id));
96 auto var_dSize =
_src_bn_.variable(
id).domainSize();
98 if (
auto entry_size = tensor->domainSize() / var_dSize; cpt.size() != entry_size)
100 "setCPTs : entry sizes of cpts does not match for node id : "
101 <<
id <<
" : " << cpt.size() <<
" != " << entry_size);
103 for (
const auto& cset: cpt) {
104 if (cset.size() == 0)
106 "setCPTs : vertices in credal set does not match for node id : "
107 <<
id <<
" with 0 vertices");
109 for (
const auto& vertex: cset) {
110 if (vertex.size() != var_dSize)
112 "setCPTs : variable modalities in cpts does "
113 "not match for node id : "
114 <<
id <<
" with vertex " << vertex <<
" : " << vertex.size()
115 <<
" != " << var_dSize);
119 for (
const auto& prob: vertex) {
125 "setCPTs : a vertex coordinates does not "
126 "sum to one for node id : "
127 <<
id <<
" with vertex " << vertex);
134 template < GUM_Numeric GUM_SCALAR >
137 const std::vector< std::vector< GUM_SCALAR > >& cpt) {
138 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(
id));
140 auto var_dSize =
_src_bn_.variable(
id).domainSize();
141 auto entry_size = tensor->domainSize() / var_dSize;
143 if (entry >= entry_size)
145 "setCPT : entry is greater or equal than entry size "
146 "(entries start at 0 up to entry_size - 1) : "
147 << entry <<
" >= " << entry_size);
149 if (cpt.size() == 0)
GUM_ERROR(
SizeError,
"setCPT : empty credal set for entry : " << entry)
151 for (
const auto& vertex: cpt) {
152 if (vertex.size() != var_dSize)
154 "setCPT : variable modalities in cpts does not "
155 "match for node id : "
156 <<
id <<
" with vertex " << vertex <<
" at entry " << entry <<
" : "
157 << vertex.size() <<
" != " << var_dSize);
161 for (
const auto& prob: vertex) {
167 "setCPT : a vertex coordinates does not sum to one for node id : "
168 <<
id <<
" at entry " << entry <<
" with vertex " << vertex);
174 std::vector< std::vector< std::vector< GUM_SCALAR > > >(entry_size));
176 if (node_cpt[entry].size() != 0)
178 "setCPT : vertices of entry id " << entry
179 <<
" already set to : " << node_cpt[entry]
180 <<
", cannot insert : " << cpt);
182 node_cpt[entry] = cpt;
187 template < GUM_Numeric GUM_SCALAR >
190 const std::vector< std::vector< GUM_SCALAR > >& cpt) {
191 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(
id));
193 auto var_dSize =
_src_bn_.variable(
id).domainSize();
194 auto entry_size = tensor->domainSize() / var_dSize;
215 "setCPT : instantiation : "
216 << ins <<
" is not valid for node id " <<
id
217 <<
" which accepts instantiations such as (order is not "
222 Idx entry = 0, jump = 1;
224 for (
Idx i = 0, end = ins.
nbrDim(); i < end; i++) {
227 entry += ins.
val(i) * jump;
232 if (entry >= entry_size)
234 "setCPT : entry is greater or equal than entry size "
235 "(entries start at 0 up to entry_size - 1) : "
236 << entry <<
" >= " << entry_size);
238 if (cpt.size() == 0)
GUM_ERROR(
SizeError,
"setCPT : empty credal set for entry : " << entry)
240 for (
const auto& vertex: cpt) {
241 if (vertex.size() != var_dSize)
243 "setCPT : variable modalities in cpts does not "
244 "match for node id : "
245 <<
id <<
" with vertex " << vertex <<
" at entry " << entry <<
" : "
246 << vertex.size() <<
" != " << var_dSize);
250 for (
const auto& prob: vertex) {
256 "setCPT : a vertex coordinates does not sum to one for node id : "
257 <<
id <<
" at entry " << entry <<
" with vertex " << vertex);
262 std::vector< std::vector< std::vector< GUM_SCALAR > > >(entry_size));
264 if (node_cpt[entry].size() != 0)
266 "setCPT : vertices of entry : " << ins <<
" id " << entry
267 <<
" already set to : " << node_cpt[entry]
268 <<
", cannot insert : " << cpt);
270 node_cpt[entry] = cpt;
275 template < GUM_Numeric GUM_SCALAR >
277 const std::vector< GUM_SCALAR >& lower,
278 const std::vector< GUM_SCALAR >& upper) {
284 "fillConstraints : sizes does not match in fillWith for node id : " <<
id);
288 template < GUM_Numeric GUM_SCALAR >
291 const std::vector< GUM_SCALAR >& lower,
292 const std::vector< GUM_SCALAR >& upper) {
293 Tensor< GUM_SCALAR >*
const tensor_min(
294 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_min_.cpt(
id)));
295 Tensor< GUM_SCALAR >*
const tensor_max(
296 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_max_.cpt(
id)));
298 auto var_dSize =
_src_bn_.variable(
id).domainSize();
300 if (lower.size() != var_dSize || upper.size() != var_dSize)
302 "setCPT : variable modalities in cpts does not match for node id : "
303 <<
id <<
" with sizes of constraints : ( " << lower.size() <<
" || "
304 << upper.size() <<
" ) != " << var_dSize);
306 auto entry_size = tensor_min->domainSize() / var_dSize;
308 if (entry >= entry_size)
310 "setCPT : entry is greater or equal than entry size "
311 "(entries start at 0 up to entry_size - 1) : "
312 << entry <<
" >= " << entry_size);
321 while (pos != entry) {
327 for (
Size i = 0; i < var_dSize; i++) {
328 tensor_min->set(min, lower[i]);
329 tensor_max->set(max, upper[i]);
335 template < GUM_Numeric GUM_SCALAR >
338 const std::vector< GUM_SCALAR >& lower,
339 const std::vector< GUM_SCALAR >& upper) {
340 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(
id));
364 "setCPT : instantiation : "
365 << ins <<
" is not valid for node id " <<
id
366 <<
" which accepts instantiations such as (order is not "
371 Idx entry = 0, jump = 1;
373 for (
Idx i = 0, end = ins.
nbrDim(); i < end; i++) {
376 entry += ins.
val(i) * jump;
402 template < GUM_Numeric GUM_SCALAR >
407 template < GUM_Numeric GUM_SCALAR >
409 return _src_bn_.variable(
id).domainSize();
414 template < GUM_Numeric GUM_SCALAR >
422 template < GUM_Numeric GUM_SCALAR >
424 const BayesNet< GUM_SCALAR >& src_max_den) {
431 template < GUM_Numeric GUM_SCALAR >
443 template < GUM_Numeric GUM_SCALAR >
448 template < GUM_Numeric GUM_SCALAR >
450 GUM_SCALAR epsi_min = 1.;
451 GUM_SCALAR epsi_max = 0.;
452 GUM_SCALAR epsi_moy = 0.;
453 GUM_SCALAR epsi_den = 0.;
455 for (
auto node:
src_bn().nodes()) {
456 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(node));
458 Tensor< GUM_SCALAR >*
const tensor_min(
459 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_min_.cpt(node)));
460 Tensor< GUM_SCALAR >*
const tensor_max(
461 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_max_.cpt(node)));
464 Size entry_size = tensor->domainSize() / var_dSize;
474 std::vector< GUM_SCALAR > vertex(var_dSize);
476 for (
Size entry = 0; entry < entry_size; entry++) {
480 else den = tensor_max->get(ins_max);
484 for (
Size modality = 0; modality < var_dSize; modality++) {
485 vertex[modality] = tensor->get(ins);
488 den += vertex[modality];
490 if (vertex[modality] < 1 && vertex[modality] > 0)
492 "bnToCredal : the BayesNet contains "
493 "probabilities and not event counts "
494 "although user precised oneNet = "
498 if (vertex[modality] > 0) nbm++;
507 for (
auto modality = vertex.cbegin(), theEnd = vertex.cend(); modality != theEnd;
515 <<
"(" <<
_epsRedund_ <<
") does not sum to one for" <<
" " << entry
517 << vertex << std::endl
518 << ins << std::endl);
526 if (beta == 0) epsilon = 0;
527 else if (den == 0 || beta == 1) epsilon = GUM_SCALAR(1.0);
528 else epsilon = GUM_SCALAR(std::pow(beta, std::log1p(den)));
533 if (epsilon > epsi_max) epsi_max = epsilon;
535 if (epsilon < epsi_min) epsi_min = epsilon;
539 for (
Size modality = 0; modality < var_dSize; modality++) {
540 if ((vertex[modality] > 0 && nbm > 1) || !keepZeroes) {
541 min = GUM_SCALAR((1. - epsilon) * vertex[modality]);
543 if (oneNet) min = GUM_SCALAR(min * 1.0 / den);
545 max = GUM_SCALAR(min + epsilon);
550 min = vertex[modality];
552 if (oneNet) min = GUM_SCALAR(min * 1.0 / den);
557 tensor_min->set(ins_min, min);
558 tensor_max->set(ins_max, max);
568 _epsilonMoy_ = (GUM_SCALAR)epsi_moy / (GUM_SCALAR)epsi_den;
573 template < GUM_Numeric GUM_SCALAR >
576 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(node));
578 auto var_dSize =
_src_bn_.variable(node).domainSize();
579 auto entry_size = tensor->domainSize() / var_dSize;
585 std::vector< GUM_SCALAR > vertex(var_dSize);
587 for (
Size entry = 0; entry < entry_size; entry++) {
591 for (
Size modality = 0; modality < var_dSize; modality++) {
592 vertex[modality] = tensor->get(ins);
594 if (vertex[modality] < 1 && vertex[modality] > 0)
596 "lagrangeNormalization : the BayesNet "
597 "contains probabilities and not event "
600 if (!zeroes && vertex[modality] == 0) { zeroes =
true; }
608 for (
Size modality = 0; modality < var_dSize; modality++) {
609 tensor->set(ins, tensor->get(ins) + 1);
617 template < GUM_Numeric GUM_SCALAR >
620 const Tensor< GUM_SCALAR >*
const tensor(&
_src_bn_.cpt(node));
622 Tensor< GUM_SCALAR >*
const tensor_min(
623 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_min_.cpt(node)));
624 Tensor< GUM_SCALAR >*
const tensor_max(
625 const_cast< Tensor< GUM_SCALAR >*
const >(&
_src_bn_max_.cpt(node)));
628 Size entry_size = tensor->domainSize() / var_dSize;
638 std::vector< GUM_SCALAR > vertex(var_dSize);
640 for (
Size entry = 0; entry < entry_size; entry++) {
644 for (
Size modality = 0; modality < var_dSize; modality++) {
645 vertex[modality] = tensor->get(ins);
647 if (vertex[modality] < 1 && vertex[modality] > 0)
649 "idmLearning : the BayesNet contains "
650 "probabilities and not event counts.");
652 den += vertex[modality];
654 if (vertex[modality] > 0) nbm++;
659 if (nbm > 1 || !keepZeroes) den += s;
663 for (
Size modality = 0; modality < var_dSize; modality++) {
664 min = vertex[modality];
667 if ((vertex[modality] > 0 && nbm > 1) || !keepZeroes) { max += s; }
669 min = GUM_SCALAR(min * 1.0 / den);
670 max = GUM_SCALAR(max * 1.0 / den);
672 tensor_min->set(ins_min, min);
673 tensor_max->set(ins_max, max);
688 template < GUM_Numeric GUM_SCALAR >
695 const Tensor< GUM_SCALAR >*
const tensor_min(&
_src_bn_min_.cpt(node));
696 const Tensor< GUM_SCALAR >*
const tensor_max(&
_src_bn_max_.cpt(node));
699 Size entry_size = tensor_min->domainSize() / var_dSize;
701 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
709 std::vector< GUM_SCALAR > lower(var_dSize);
710 std::vector< GUM_SCALAR > upper(var_dSize);
715 for (
Size entry = 0; entry < entry_size; entry++) {
716 for (
Size modality = 0; modality < var_dSize; modality++, ++ins_min, ++ins_max) {
717 lower[modality] = tensor_min->get(ins_min);
718 upper[modality] = tensor_max->get(ins_max);
721 bool all_equals =
true;
722 std::vector< std::vector< GUM_SCALAR > > vertices;
724 for (
Size modality = 0; modality < var_dSize; modality++) {
725 if (std::fabs(upper[modality] - lower[modality]) < epsilon)
continue;
728 std::vector< GUM_SCALAR > vertex(var_dSize);
729 vertex[modality] = upper[modality];
731 for (
Size mod = 0; mod < var_dSize; mod++) {
732 if (modality != mod) vertex[mod] = lower[mod];
735 GUM_SCALAR total = 0;
737 auto vsize = vertex.size();
739 for (
Size i = 0; i < vsize; i++)
742 if (std::fabs(total - 1.) > epsilon)
745 <<
" does not sum to one for " << entry << std::endl
746 << vertex << std::endl);
748 vertices.push_back(vertex);
752 std::vector< GUM_SCALAR > vertex(var_dSize);
754 for (
Size modality = 0; modality < var_dSize; modality++)
755 vertex[modality] = lower[modality];
757 GUM_SCALAR total = 0.;
759 auto vsize = vertex.size();
761 for (
Size i = 0; i < vsize; i++)
764 if (std::fabs(total - 1.) > epsilon)
767 <<
" does not sum to one for " << entry << std::endl
768 << vertex << std::endl);
770 vertices.push_back(vertex);
773 var_cpt[entry] = vertices;
785 template < GUM_Numeric GUM_SCALAR >
794 const Tensor< GUM_SCALAR >*
const tensor_min(&
_src_bn_min_.cpt(node));
795 const Tensor< GUM_SCALAR >*
const tensor_max(&
_src_bn_max_.cpt(node));
798 Size entry_size = tensor_min->domainSize() / var_dSize;
800 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
808 lrsWrapper.
setUpH(var_dSize);
810 for (
Size entry = 0; entry < entry_size; entry++) {
811 for (
Size modality = 0; modality < var_dSize; modality++) {
812 if (tensor_min->get(ins_min) > tensor_max->get(ins_max)) {
815 <<
_src_bn_.variable(node).name() <<
" (at " << ins_min
816 <<
"), the min is greater than the max : " << tensor_min->get(ins_min)
817 <<
">" << tensor_max->get(ins_max) <<
".");
819 lrsWrapper.
fillH(tensor_min->get(ins_min), tensor_max->get(ins_max), modality);
838 template < GUM_Numeric GUM_SCALAR >
845 const Tensor< GUM_SCALAR >*
const tensor_min(&
_src_bn_min_.cpt(node));
846 const Tensor< GUM_SCALAR >*
const tensor_max(&
_src_bn_max_.cpt(node));
848 auto var_dSize =
_src_bn_.variable(node).domainSize();
849 auto entry_size = tensor_min->domainSize() / var_dSize;
851 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
860 for (
Size entry = 0; entry < entry_size; entry++) {
861 std::vector< std::vector< GUM_SCALAR > > vertices;
862 std::vector< GUM_SCALAR > vertex(var_dSize);
864 std::vector< std::vector< GUM_SCALAR > > inequalities(
866 std::vector< GUM_SCALAR >(var_dSize + 1, 0));
868 std::vector< GUM_SCALAR > sum_ineq1(var_dSize + 1, -1);
869 std::vector< GUM_SCALAR > sum_ineq2(var_dSize + 1, 1);
873 bool isInterval =
false;
875 for (
Size modality = 0; modality < var_dSize; modality++) {
876 inequalities[modality * 2][0] = -tensor_min->get(ins_min);
877 inequalities[modality * 2 + 1][0] = tensor_max->get(ins_max);
878 inequalities[modality * 2][modality + 1] = 1;
879 inequalities[modality * 2 + 1][modality + 1] = -1;
881 vertex[modality] = inequalities[modality * 2 + 1][0];
884 && (-inequalities[modality * 2][0] != inequalities[modality * 2 + 1][0]))
891 inequalities.push_back(sum_ineq1);
892 inequalities.push_back(sum_ineq2);
895 vertices.push_back(vertex);
900 }
catch (
const std::exception& err) {
901 std::cout << err.what() << std::endl;
906 if (entry == 0 && vertices.size() >= 2) {
907 auto tmp = vertices[0];
908 vertices[0] = vertices[1];
912 var_cpt[entry] = vertices;
929 template < GUM_Numeric GUM_SCALAR >
931 std::string_view max_path) {
934 std::string minfilename(min_path);
935 std::string maxfilename(max_path);
936 std::ofstream min_file(minfilename.c_str(), std::ios::out | std::ios::trunc);
937 std::ofstream max_file(maxfilename.c_str(), std::ios::out | std::ios::trunc);
939 if (!min_file.good())
940 GUM_ERROR(
IOError,
"bnToCredal() : could not open stream : min_file : " << minfilename);
942 if (!max_file.good()) {
944 GUM_ERROR(
IOError,
"bnToCredal() : could not open stream : min_file : " << maxfilename);
961 template < GUM_Numeric GUM_SCALAR >
964 auto bin_bn =
new BayesNet< GUM_SCALAR >();
968 auto credalNet_bin_cpt
976 credalNet_current_cpt;
987 bin_bn->beginTopologyTransformation();
990 auto var_dSize =
current_bn->variable(node).domainSize();
992 if (var_dSize != 2) {
995 superiorPow(
static_cast< unsigned long >(var_dSize), b, c);
998 std::string bit_name;
999 std::vector< NodeId > bits(nb_bits);
1001 for (
Size bit = 0; bit < nb_bits; bit++) {
1002 bit_name =
current_bn->variable(node).name() +
"-b";
1003 bit_name += std::to_string(bit);
1006 NodeId iD = bin_bn->add(var_bit);
1014 const std::string bit_name =
current_bn->variable(node).name();
1016 const NodeId iD = bin_bn->add(var_bit);
1018 _var_bits_.insert(node, std::vector< NodeId >(1, iD));
1026 parent_bit < spbits;
1036 const auto bitsize =
_var_bits_[node].size();
1038 for (
Size bit_c = 1; bit_c < bitsize; bit_c++)
1039 for (
Size bit_p = 0; bit_p < bit_c; bit_p++)
1043 bin_bn->endTopologyTransformation();
1049 for (
Size var = 0; var < varsize; var++) {
1052 for (
Size i = 0; i < bitsize; i++) {
1053 Tensor< GUM_SCALAR >
const* tensor(&bin_bn->cpt(
_var_bits_[var][i]));
1057 auto entry_size = tensor->domainSize() / 2;
1058 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
1062 for (
Size conf = 0; conf < entry_size; conf++) {
1063 std::vector< std::vector< GUM_SCALAR > > pvar_cpt;
1064 auto verticessize = (*credalNet_current_cpt)[var][old_conf].size();
1066 for (
Size old_distri = 0; old_distri < verticessize; old_distri++) {
1067 const std::vector< GUM_SCALAR >& vertex
1068 = (*credalNet_current_cpt)[var][old_conf][old_distri];
1069 auto vertexsize = vertex.size();
1071 std::vector< Idx > incc(vertexsize, 0);
1073 for (
Size preced = 0; preced < i; preced++) {
1074 auto bit_pos = ins.
pos(bin_bn->variable(
_var_bits_[var][preced]));
1075 auto val = ins.
val(bit_pos);
1080 if (val == 0) elem = 0;
1083 while (elem < vertexsize) {
1087 if (elem % pas == 0) elem += pas;
1093 std::vector< GUM_SCALAR > distri(2, 0);
1096 for (
Size elem = 0; elem < vertexsize; elem++) {
1097 if (elem % pas == 0) pos = -pos;
1099 if (incc[elem] == i)
1100 (pos < 0) ? (distri[0] += vertex[elem]) : (distri[1] += vertex[elem]);
1104 GUM_SCALAR den = distri[0] + distri[1];
1115 pvar_cpt.push_back(distri);
1119 std::vector< std::vector< GUM_SCALAR > > vertices(2, std::vector< GUM_SCALAR >(2, 1));
1122 const auto new_verticessize = pvar_cpt.size();
1124 for (
Size v = 0; v < new_verticessize; v++) {
1125 if (pvar_cpt[v][1] < vertices[0][1]) vertices[0][1] = pvar_cpt[v][1];
1127 if (pvar_cpt[v][1] > vertices[1][1]) vertices[1][1] = pvar_cpt[v][1];
1130 vertices[0][0] = 1 - vertices[0][1];
1131 vertices[1][0] = 1 - vertices[1][1];
1133 pvar_cpt = vertices;
1135 var_cpt[conf] = pvar_cpt;
1142 if (old_conf == (*credalNet_current_cpt)[var].size()) old_conf = 0;
1145 credalNet_bin_cpt->insert(
_var_bits_[var][i], var_cpt);
1149 bin_bn->beginTopologyTransformation();
1154 for (
Size i = 0; i < old_varsize; i++) {
1158 if (bitsize == 1)
continue;
1160 auto old_card =
_src_bn_.variable(i).domainSize();
1162 for (
Size mod = 0; mod < old_card; mod++) {
1163 auto ss_str = std::format(
"{}-v{}",
_src_bn_.variable(i).name(), mod);
1166 const NodeId indic = bin_bn->add(var);
1169 for (
Size bit = 0; bit < bitsize; bit++)
1175 std::vector< std::vector< std::vector< GUM_SCALAR > > > icpt(num);
1177 for (
Size entry = 0; entry < num; entry++) {
1178 std::vector< std::vector< GUM_SCALAR > > vertices(1, std::vector< GUM_SCALAR >(2, 0));
1180 if (mod == entry) vertices[0][1] = 1;
1181 else vertices[0][0] = 1;
1183 icpt[entry] = vertices;
1186 credalNet_bin_cpt->insert(indic, icpt);
1192 bin_bn->endTopologyTransformation();
1212 template < GUM_Numeric GUM_SCALAR >
1220 template < GUM_Numeric GUM_SCALAR >
1226 template < GUM_Numeric GUM_SCALAR >
1234 template < GUM_Numeric GUM_SCALAR >
1240 template < GUM_Numeric GUM_SCALAR >
1245 template < GUM_Numeric GUM_SCALAR >
1251 template < GUM_Numeric GUM_SCALAR >
1260 std::vector< GUM_SCALAR > min(pConf);
1261 std::vector< GUM_SCALAR > max(pConf);
1263 for (
Size pconf = 0; pconf < pConf; pconf++) {
1271 GUM_SCALAR delta = v1 - v2;
1272 min[pconf] = (delta >= 0) ? v2 : v1;
1273 max[pconf] = (delta >= 0) ? v1 : v2;
1283 template < GUM_Numeric GUM_SCALAR >
1284 const std::vector< std::vector< GUM_SCALAR > >&
1289 template < GUM_Numeric GUM_SCALAR >
1290 const std::vector< std::vector< GUM_SCALAR > >&
1295 template < GUM_Numeric GUM_SCALAR >
1300 template < GUM_Numeric GUM_SCALAR >
1305 template < GUM_Numeric GUM_SCALAR >
1310 template < GUM_Numeric GUM_SCALAR >
1312 std::stringstream output;
1317 for (
auto node: bn_ptr->nodes()) {
1318 const Tensor< GUM_SCALAR >* tensor(&bn_ptr->cpt(node));
1319 auto pconfs = tensor->domainSize() / bn_ptr->variable(node).domainSize();
1321 output <<
"\n" << bn_ptr->variable(node) <<
"\n";
1325 ins.
erase(bn_ptr->variable(node));
1328 for (
Size pconf = 0; pconf < pconfs; pconf++) {
1329 output << ins <<
" : ";
1330 output << (*cpt_ptr)[node][pconf] <<
"\n";
1332 if (pconf < pconfs - 1) ++ins;
1338 return output.str();
1341 template < GUM_Numeric GUM_SCALAR >
1346 template < GUM_Numeric GUM_SCALAR >
1353 for (
const auto node: bn.nodes()) {
1354 const auto& name = bn.variable(node).name();
1358 "(" + std::to_string(node) +
") " + name);
1362 writer.
node(name, attributes);
1365 for (
const auto& arc: bn.arcs()) {
1369 std::to_string(arc.tail()) +
" → "
1370 + std::to_string(arc.head()));
1372 writer.
edge(bn.variable(arc.tail()).name(), bn.variable(arc.head()).name(), attributes);
1375 return writer.
str();
1378 template < GUM_Numeric GUM_SCALAR >
1385 template < GUM_Numeric GUM_SCALAR >
1394 template < GUM_Numeric GUM_SCALAR >
1421 template < GUM_Numeric GUM_SCALAR >
1423 std::string_view src_max_den) {
1427 if (src_max_den.compare(
"") != 0) other = src_max_den;
1428 else other = src_min_num;
1438 template < GUM_Numeric GUM_SCALAR >
1440 const BayesNet< GUM_SCALAR >& src_max_den) {
1444 if (src_max_den.size() > 0)
_src_bn_max_ = src_max_den;
1448 template < GUM_Numeric GUM_SCALAR >
1450 const std::vector< std::vector< std::vector< GUM_SCALAR > > >& var_cpt)
const {
1451 Size vertices_size = 0;
1453 for (
auto entry = var_cpt.cbegin(), theEnd = var_cpt.cend(); entry != theEnd; ++entry) {
1454 if (entry->size() > vertices_size) vertices_size =
Size(entry->size());
1457 return int(vertices_size);
1460 template < GUM_Numeric GUM_SCALAR >
1464 for (
auto node: bn_ptr->nodes())
1465 dest.add(bn_ptr->variable(node));
1467 dest.beginTopologyTransformation();
1469 for (
auto node: bn_ptr->nodes()) {
1470 for (
auto parent_idIt: bn_ptr->cpt(node).variablesSequence()) {
1471 if (bn_ptr->nodeId(*parent_idIt) != node) dest.addArc(bn_ptr->nodeId(*parent_idIt), node);
1475 dest.endTopologyTransformation();
1530 template < GUM_Numeric GUM_SCALAR >
1532 std::vector< std::vector< GUM_SCALAR > >& v_rep)
const {
1542 std::ofstream h_file(sinefile.c_str(), std::ios::out | std::ios::trunc);
1545 GUM_ERROR(
IOError,
" __H2Vlrs : could not open lrs input file : " << sinefile)
1547 h_file <<
"H - representation\n";
1548 h_file <<
"begin\n";
1549 h_file << h_rep.size() <<
' ' << h_rep[0].size() <<
" rational\n";
1551 for (
auto it = h_rep.cbegin(), theEnd = h_rep.cend(); it != theEnd; ++it) {
1552 for (
auto it2 = it->cbegin(), theEnd2 = it->cend(); it2 != theEnd2; ++it2) {
1558 ((*it2 > 0) ? *it2 : -*it2),
1562 h_file << ((*it2 > 0) ? num : -num) <<
'/' << den <<
' ';
1572 std::string extfile(sinefile);
1575 std::string lrs_arg0 =
"lrs";
1576 std::string lrs_arg1 = sinefile;
1577 std::string lrs_arg2 = extfile;
1578 char* lrs_argv[3] = {lrs_arg0.data(), lrs_arg1.data(), lrs_arg2.data()};
1581 lrs_main(3, lrs_argv);
1584 std::ifstream v_file(extfile.c_str() , std::ios::in);
1586 if (!v_file.good())
GUM_ERROR(
IOError,
" __H2Vlrs : could not open lrs output file : ")
1588 std::string line, tmp;
1590 GUM_SCALAR probability;
1592 std::string::size_type pos;
1593 bool keep_going =
true;
1596 std::vector< GUM_SCALAR > vertex;
1598 v_file.ignore(256,
'l');
1600 while (v_file.good() && keep_going) {
1601 getline(v_file, line);
1603 if (line.size() == 0)
continue;
1604 else if (line.compare(
"end") == 0) {
1614 }
else if (line[1] !=
'1') {
1616 " __H2Vlrs : reading something other than a vertex from "
1617 "lrs output file : ");
1620 line = line.substr(2);
1621 cstr =
new char[line.size() + 1];
1622 strcpy(cstr, line.c_str());
1624 p = strtok(cstr,
" ");
1626 while (p !=
nullptr) {
1629 if (tmp.compare(
"1") == 0 || tmp.compare(
"0") == 0)
1630 probability = GUM_SCALAR(atof(tmp.c_str()));
1632 pos = tmp.find(
"/");
1633 probability = GUM_SCALAR(atof(tmp.substr(0, pos).c_str())
1634 / atof(tmp.substr(pos + 1, tmp.size()).c_str()));
1637 vertex.push_back(probability);
1638 p = strtok(
nullptr,
" ");
1649 const auto nsize = v_rep.size();
1650 const auto real_nb_threads = std::min(nb_threads, nsize);
1654 std::vector< Size > t_redund(real_nb_threads);
1657 auto threadedExec = [
this, ranges, &t_redund, vertex, v_rep](
const std::size_t this_thread,
1658 const std::size_t nb_threads) {
1659 const auto vsize = vertex.size();
1660 auto& thread_redund = t_redund[this_thread];
1662 for (
Idx i = ranges[this_thread].first, end = ranges[this_thread].second; i < end; i++) {
1664 for (
Idx modality = 0; modality < vsize; ++modality) {
1665 if (std::fabs(vertex[modality] - v_rep[i][modality]) >
_epsRedund_) {
1671 if (thread_redund)
return;
1679 bool is_redund =
false;
1680 for (
const auto thread_redund: t_redund) {
1681 if (thread_redund) {
1723 if (!is_redund) v_rep.push_back(vertex);
1730 if (std::remove(sinefile.c_str()) != 0)
GUM_ERROR(
IOError,
"error removing : " + sinefile)
1732 if (std::remove(extfile.c_str()) != 0)
GUM_ERROR(
IOError,
"error removing : " + extfile)
1735 template < GUM_Numeric GUM_SCALAR >
1743 for (
auto node: bn_ptr->nodes()) {
1745 if (nodeType_ptr->
exists(node))
continue;
1747 bool precise =
true, vacuous =
true;
1749 for (
auto entry = (*cpt_ptr)[node].cbegin(), theEnd2 = (*cpt_ptr)[node].cend();
1752 auto vertices = entry->size();
1753 auto var_dSize = (*entry)[0].size();
1755 if (precise && vertices > 1) precise =
false;
1757 if (vacuous && vertices == var_dSize) {
1758 std::vector< bool > elem(var_dSize,
false);
1760 for (
auto vertex = entry->cbegin(), vEnd = entry->cend(); vertex != vEnd; ++vertex) {
1761 for (
auto probability = vertex->cbegin(), pEnd = vertex->cend(); probability != pEnd;
1763 if (*probability == 1) {
1764 elem[probability - vertex->begin()] =
true;
1770 for (
auto probability = elem.cbegin(); probability != elem.cend(); ++probability)
1771 if (*probability ==
false) vacuous =
false;
1776 if (vacuous ==
false && precise ==
false) {
Definition of templatized reader of BIF files for Bayesian networks.
Size proceed() override
parse.
Writes a IBayesNet in the BIF format.
void write(std::ostream &output, IBayesNet< GUM_SCALAR > &bn)
Writes a Bayesian network in the output stream.
Exception base for CPT error.
double epsilonStandard() const noexcept
virtual Size domainSize() const =0
Exception : a similar element already exists.
Base class for all aGrUM's exceptions.
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
void clear()
Removes all the elements in the hash table.
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
Exception : input/output problem.
Class for assigning/browsing values to tuples of discrete variables.
const Sequence< const DiscreteVariable * > & variablesSequence() const final
Returns the sequence of DiscreteVariable of this instantiation.
Idx pos(const DiscreteVariable &v) const final
Returns the position of the variable v.
Instantiation()
Default constructor: creates an empty tuple.
void erase(const DiscreteVariable &v) final
Removes a variable from the Instantiation.
void reorder(const Sequence< const DiscreteVariable * > &v)
Reorder vars of this instantiation giving the order in v.
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.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Idx nbrDim() const final
Returns the number of variables in the Instantiation.
bool forgetMaster()
Deassociate the master MultiDimAdressable, if any.
Exception : operation not allowed.
static void farey(int64_t &numerator, int64_t &denominator, const GUM_SCALAR &number, const int64_t &den_max=1000000L, const GUM_SCALAR &zero=static_cast< GUM_SCALAR >(config().epsilonStandard()))
Find the rational close enough to a given ( decimal ) number in [-1,1] and whose denominator is not h...
Exception : problem with size.
void _H2Vlrs_(const std::vector< std::vector< GUM_SCALAR > > &h_rep, std::vector< std::vector< GUM_SCALAR > > &v_rep) const
void _initParams_()
Initialize private constant variables after the Constructor has been called.
GUM_SCALAR _epsilonMoy_
The average perturbation of the BayesNet provided as input for this CredalNet.
void setCPTs(const NodeId &id, const std::vector< std::vector< std::vector< GUM_SCALAR > > > &cpt)
Set the vertices of the credal sets ( all of the conditionals ) of a given node
GUM_SCALAR _deltaC_
5 by default, used by fracC as number of decimals.
Size domainSize(const NodeId &id)
Get the cardinality of a node
std::string toDot() const
BayesNet< GUM_SCALAR > _src_bn_max_
BayesNet used to store upper probabilities.
void intervalToCredalWithFiles()
void _initCNNets_(std::string_view src_min_num, std::string_view src_max_den)
Initialize private BayesNet variables after the Constructor has been called.
BayesNet< GUM_SCALAR > * _current_bn_
Up-to-date BayesNet (used as a DAG).
void _intervalToCredal_()
Computes the vertices of each credal set according to their interval definition (does not use lrs).
std::string toString() const
bool _hasComputedBinaryCPTMinMax_
Used by L2U, to know if lower and upper probabilities over the second modality has been stored in ord...
NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > _credalNet_src_cpt_
This CredalNet original CPTs.
const GUM_SCALAR & epsilonMax() const
void _bnCopy_(BayesNet< GUM_SCALAR > &bn_dest)
bool hasComputedBinaryCPTMinMax() const
GUM_SCALAR _precision_
Precision used by frac.
const NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > & credalNet_currentCpt() const
void bnToCredal(GUM_SCALAR beta, bool oneNet, bool keepZeroes)
Perturbates the BayesNet provided as input for this CredalNet by generating intervals instead of poin...
void intervalToCredal()
Computes the vertices of each credal set according to their interval definition (uses lrs).
const GUM_SCALAR & epsilonMean() const
std::vector< std::vector< GUM_SCALAR > > _binCptMin_
Used with binary networks to speed-up L2U inference.
void saveBNsMinMax(std::string_view min_path, std::string_view max_path)
If this CredalNet was built over a perturbed BayesNet, one can save the intervals as two BayesNet.
void approximatedBinarization()
Approximate binarization.
const BayesNet< GUM_SCALAR > & src_bn() const
int _find_dNode_card_(const std::vector< std::vector< std::vector< GUM_SCALAR > > > &var_cpt) const
BayesNet< GUM_SCALAR > _src_bn_
Original BayesNet (used as a DAG).
void computeBinaryCPTMinMax()
Used with binary networks to speed-up L2U inference.
const NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > & credalNet_srcCpt() const
NodeType currentNodeType(const NodeId &id) const
NodeProperty< NodeType > _original_nodeType_
The NodeType of each node from the ORIGINAL network.
void lagrangeNormalization()
Normalize counts of a BayesNet storing counts of each events such that no probability is 0.
NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > * _credalNet_current_cpt_
This CredalNet up-to-date CPTs.
bool isSeparatelySpecified() const
void _sort_varType_()
Set the NodeType of each node
void idmLearning(const Idx s=0, const bool keepZeroes=false)
Learns parameters from a BayesNet storing counts of events.
GUM_SCALAR _epsilonMax_
The highest perturbation of the BayesNet provided as input for this CredalNet.
std::vector< std::vector< GUM_SCALAR > > _binCptMax_
Used with binary networks to speed-up L2U inference.
NodeType nodeType(const NodeId &id) const
Instantiation instantiation(const NodeId &id)
Get an Instantiation from a node id, useful to fill the constraints of the network
bool _separatelySpecified_
TRUE if this CredalNet is separately and interval specified, FALSE otherwise.
void setCPT(const NodeId &id, const Size &entry, const std::vector< std::vector< GUM_SCALAR > > &cpt)
Set the vertices of one credal set of a given node ( any instantiation index )
NodeProperty< std::vector< NodeId > > _var_bits_
Corresponding bits of each variable.
const std::vector< std::vector< GUM_SCALAR > > & get_binaryCPT_max() const
Used with binary networks to speed-up L2U inference.
BayesNet< GUM_SCALAR > _src_bn_min_
BayesNet used to store lower probabilities.
NodeId addVariable(std::string_view name, const Size &card)
Adds a discrete node into the network.
const BayesNet< GUM_SCALAR > & current_bn() const
void addArc(const NodeId &tail, const NodeId &head)
Adds an arc between two nodes.
const std::vector< std::vector< GUM_SCALAR > > & get_binaryCPT_min() const
Used with binary networks to speed-up L2U inference.
void fillConstraints(const NodeId &id, const std::vector< GUM_SCALAR > &lower, const std::vector< GUM_SCALAR > &upper)
Set the interval constraints of the credal sets of a given node (all instantiations )
GUM_SCALAR _epsilonMin_
The lowest perturbation of the BayesNet provided as input for this CredalNet.
const GUM_SCALAR & epsilonMin() const
NodeProperty< NodeType > * _current_nodeType_
The NodeType of each node from the up-to-date network.
GUM_SCALAR _denMax_
Highest possible denominator allowed when using farey.
void fillConstraint(const NodeId &id, const Idx &entry, const std::vector< GUM_SCALAR > &lower, const std::vector< GUM_SCALAR > &upper)
Set the interval constraints of a credal set of a given node ( from an instantiation index )
GUM_SCALAR _epsRedund_
Value under which a decimal number is considered to be zero when computing redundant vertices.
GUM_SCALAR _precisionC_
1e6 by default, used by fracC as precision.
NodeType
NodeType to speed-up computations in some algorithms.
CredalNet()
Constructor used to create a CredalNet step by step, i.e.
GUM_SCALAR _epsF_
Value under which a decimal number is considered to be zero when using farey.
Class template acting as a wrapper for Lexicographic Reverse Search by David Avis.
const matrix & getOutput() const
Get the output matrix solution of the problem.
void H2V()
H-representation to V-representation.
void fillH(const GUM_SCALAR &min, const GUM_SCALAR &max, const Size &modal)
Creates the H-representation of min <= p(X=modal | .) <= max and add it to the problem input _input_.
void setUpH(const Size &card)
Sets up an H-representation.
void nextHInput()
Reset the wrapper for next computation for a H-representation with the same variable cardinality and ...
The options given to a toDot(const DotOptions&).
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
const DotNodeOptions * node(Size node) const
the options of a node, or nullptr if none was given for it
Writes a graph in the dot language, statement after statement, in the order of the calls.
void edge(std::string_view from, std::string_view to, const DotAttributes &attributes={})
an edge from from to to (-> in a directed graph, -- in an undirected one).
std::string str() const
The graph written so far, closed. It can be called at any moment, and the writer can be used after.
void node(std::string_view id, const DotAttributes &attributes={})
a node, whose identifier is id (quoted).
Typed, documented, sectioned configuration singleton read from an .ini content.
Class representing Credal Networks.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size Idx
Type for indexes.
Size NodeId
Type for node ids.
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
GUM_SHARED_PUBLIC uint64_t int2Pow(uint64_t exponent)
Specialized base 2 pow function with integer.
GUM_SHARED_PUBLIC void superiorPow(unsigned long card, unsigned long &num_bits, unsigned long &new_card)
Compute the superior and closest power of two of an integer.
std::string getUniqueFileName()
Returns a path to a unique file name.
namespace for all credal networks entities
DotAttributes nodeAttributes(const DotStyle &style, const DotNodeOptions *options, std::string_view defaultLabel, std::string_view defaultTooltip)
The attributes of a node : its label and tooltip, and its colors if the options give some.
void writePreamble(DotWriter &writer, const DotStyle &style, const DotOptions &options, std::string_view defaultLabel)
Writes the beginning of a graph, as pyAgrum displays it.
void addDefaultAttribute(DotAttributes &attributes, std::string_view key, std::string_view value)
Adds an attribute at the beginning of the list, unless the list already gives a value for this key : ...
DotAttributes arcAttributes(const DotArcOptions *options)
The attributes of an arc or an edge given by the options : color, penwidth, label,...
gum is the global namespace for all aGrUM entities
std::vector< std::pair< Idx, Idx > > dispatchRangeToThreads(const Idx beg, const Idx end, const unsigned int nb_threads)
returns a vector equally splitting elements of a range among threads
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
bool isCloseToOne(T x, T tol=static_cast< T >(config().epsilonFine()))
Is |x - 1| <= tol ? By default, tol is the key core.epsilonFine of the configuration.
unsigned int getNumberOfThreads()
returns the max number of threads used by default when entering the next parallel region
static DotStyle readCredalNet()
the style of the credal networks : the colors of the nodes are the ones of the section credalnet
static void execute(std::size_t nb_threads, FUNCTION exec_func, ARGS &&... func_args)
executes a function using several threads
static int nbRunningThreadsExecutors()
indicates how many threadExecutors are currently running
Utilities for manipulating strings.