aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
multipleInferenceEngine_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
47
48namespace gum {
49 namespace credal {
50
51 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
57
58 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
62
63 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
65 const Size& num_threads,
66 const bool _storeVertices_,
67 const bool _storeBNOpt_) {
68 workingSet_.clear();
69 workingSet_.resize(num_threads, nullptr);
70 workingSetE_.clear();
71 workingSetE_.resize(num_threads, nullptr);
72
73 l_marginalMin_.clear();
74 l_marginalMin_.resize(num_threads);
75 l_marginalMax_.clear();
76 l_marginalMax_.resize(num_threads);
77 l_expectationMin_.clear();
78 l_expectationMin_.resize(num_threads);
79 l_expectationMax_.clear();
80 l_expectationMax_.resize(num_threads);
81
82 l_clusters_.clear();
83 l_clusters_.resize(num_threads);
84
85 if (_storeVertices_) {
86 l_marginalSets_.clear();
87 l_marginalSets_.resize(num_threads);
88 }
89
90 if (_storeBNOpt_) {
91 for (Size ptr = 0; ptr < this->l_optimalNet_.size(); ptr++)
92 if (this->l_optimalNet_[ptr] != nullptr) delete l_optimalNet_[ptr];
93
94 l_optimalNet_.clear();
95 l_optimalNet_.resize(num_threads);
96 }
97
98 l_modal_.clear();
99 l_modal_.resize(num_threads);
100
102 this->oldMarginalMin_ = this->marginalMin_;
103 this->oldMarginalMax_.clear();
104 this->oldMarginalMax_ = this->marginalMax_;
105
106 // init the random number generators
107 generators_.clear();
108 generators_.resize(num_threads);
109 auto seed = currentRandomGeneratorValue();
110 for (auto& generator: generators_) {
111 generator.seed(seed);
112 seed = generator();
113 }
114 }
115
116 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
118 Size tId,
119 const NodeId& id,
120 const std::vector< GUM_SCALAR >& vertex,
121 const bool& elimRedund) {
122 // save E(X) if we don't save vertices
123 if (!_infE_::storeVertices_ && !l_modal_[tId].empty()) {
124 std::string var_name = workingSet_[tId]->variable(id).name();
125 auto delim = var_name.find_first_of("_");
126 var_name = var_name.substr(0, delim);
127
128 if (l_modal_[tId].exists(var_name)) {
129 GUM_SCALAR exp = 0;
130 Size vsize = Size(vertex.size());
131
132 for (Size mod = 0; mod < vsize; mod++)
133 exp += vertex[mod] * l_modal_[tId][var_name][mod];
134
135 if (exp > l_expectationMax_[tId][id]) l_expectationMax_[tId][id] = exp;
136
137 if (exp < l_expectationMin_[tId][id]) l_expectationMin_[tId][id] = exp;
138 }
139 } // end of : if modal (map) not empty
140
141 bool newOne = false;
142 bool added = false;
143 bool result = false;
144 // for burn in, we need to keep checking on local marginals and not global
145 // ones
146 // (faster inference)
147 // we also don't want to store dbn for observed variables since there will
148 // be a
149 // huge number of them (probably all of them).
150 Size vsize = Size(vertex.size());
151
152 for (Size mod = 0; mod < vsize; mod++) {
153 if (vertex[mod] < l_marginalMin_[tId][id][mod]) {
154 l_marginalMin_[tId][id][mod] = vertex[mod];
155 newOne = true;
156
157 if (_infE_::storeBNOpt_ && !_infE_::evidence_.exists(id)) {
158 std::vector< Size > key(3);
159 key[0] = id;
160 key[1] = mod;
161 key[2] = 0;
163 if (l_optimalNet_[tId]->insert(key, true)) result = true;
164 }
165 }
166
167 if (vertex[mod] > l_marginalMax_[tId][id][mod]) {
168 l_marginalMax_[tId][id][mod] = vertex[mod];
169 newOne = true;
170
171 if (_infE_::storeBNOpt_ && !_infE_::evidence_.exists(id)) {
172 std::vector< Size > key(3);
173 key[0] = id;
174 key[1] = mod;
175 key[2] = 1;
176
177 if (l_optimalNet_[tId]->insert(key, true)) result = true;
178 }
179 } else if (vertex[mod] == l_marginalMin_[tId][id][mod]
180 || vertex[mod] == l_marginalMax_[tId][id][mod]) {
181 newOne = true;
182
183 if (_infE_::storeBNOpt_ && vertex[mod] == l_marginalMin_[tId][id][mod]
184 && !_infE_::evidence_.exists(id)) {
185 std::vector< Size > key(3);
186 key[0] = id;
187 key[1] = mod;
188 key[2] = 0;
189
190 if (l_optimalNet_[tId]->insert(key, false)) result = true;
192
193 if (_infE_::storeBNOpt_ && vertex[mod] == l_marginalMax_[tId][id][mod]
194 && !_infE_::evidence_.exists(id)) {
195 std::vector< Size > key(3);
196 key[0] = id;
197 key[1] = mod;
198 key[2] = 1;
199
200 if (l_optimalNet_[tId]->insert(key, false)) result = true;
201 }
202 }
203
204 // store point to compute credal set vertices.
205 // check for redundancy at each step or at the end ?
206 if (_infE_::storeVertices_ && !added && newOne) {
207 _updateThreadCredalSets_(tId, id, vertex, elimRedund);
208 added = true;
209 }
210 }
211
212 // if all variables didn't get better marginals, we will delete
213 if (_infE_::storeBNOpt_ && result) return true;
214
215 return false;
216 }
218 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
220 Size tId,
221 const NodeId& id,
222 const std::vector< GUM_SCALAR >& vertex,
223 const bool& elimRedund) {
224 auto& nodeCredalSet = l_marginalSets_[tId][id];
225 Size dsize = Size(vertex.size());
226
227 bool eq = true;
228 const double epsilon = config().epsilonStandard();
229
230 for (auto it = nodeCredalSet.cbegin(), itEnd = nodeCredalSet.cend(); it != itEnd; ++it) {
231 eq = true;
232
233 for (Size i = 0; i < dsize; i++) {
234 if (std::fabs(vertex[i] - (*it)[i]) > epsilon) {
235 eq = false;
236 break;
237 }
238 }
239
240 if (eq) break;
241 }
242
243 if (!eq || nodeCredalSet.size() == 0) {
244 nodeCredalSet.push_back(vertex);
245 return;
246 } else return;
250 if (nodeCredalSet.size() == 1) return;
251
252 // check that the point and all previously added ones are not inside the
253 // actual
254 // polytope
255 auto itEnd = std::remove_if(
256 nodeCredalSet.begin(),
257 nodeCredalSet.end(),
258 [&](const std::vector< GUM_SCALAR >& v) -> bool {
259 for (auto jt = v.cbegin(),
260 jtEnd = v.cend(),
261 minIt = l_marginalMin_[tId][id].cbegin(),
262 minItEnd = l_marginalMin_[tId][id].cend(),
263 maxIt = l_marginalMax_[tId][id].cbegin(),
264 maxItEnd = l_marginalMax_[tId][id].cend();
265 jt != jtEnd && minIt != minItEnd && maxIt != maxItEnd;
266 ++jt, ++minIt, ++maxIt) {
267 if ((std::fabs(*jt - *minIt) < epsilon || std::fabs(*jt - *maxIt) < epsilon)
268 && std::fabs(*minIt - *maxIt) > epsilon)
269 return false;
270 }
271 return true;
272 });
273
274 nodeCredalSet.erase(itEnd, nodeCredalSet.end());
275
276 // we need at least 2 points to make a convex combination
277 if (!elimRedund || nodeCredalSet.size() <= 2) return;
278
279 // there may be points not inside the polytope but on one of it's facet,
280 // meaning it's still a convex combination of vertices of this facet. Here
281 // we need lrs.
282 Size setSize = Size(nodeCredalSet.size());
283
284 LRSWrapper< GUM_SCALAR > lrsWrapper;
285 lrsWrapper.setUpV(dsize, setSize);
286
287 for (const auto& vtx: nodeCredalSet)
288 lrsWrapper.fillV(vtx);
289
290 lrsWrapper.elimRedundVrep();
291
292 l_marginalSets_[tId][id] = lrsWrapper.getOutput();
293 }
294
295 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
297 // compute the max number of threads to use (avoid nested threads)
298 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
299 ? this->threadRanges_.size() - 1
300 : 1; // no nested multithreading
301
302 // create the function to be executed by the threads
303 auto threadedExec = [this](const std::size_t this_thread,
304 const std::size_t nb_threads,
305 const std::vector< std::pair< Idx, Idx > >& ranges) {
306 auto i = this->threadRanges_[this_thread].first;
307 auto j = this->threadRanges_[this_thread].second;
308 auto domain_size = this->marginalMax_[i].size();
309 const auto end_i = this->threadRanges_[this_thread + 1].first;
310 auto end_j = this->threadRanges_[this_thread + 1].second;
311 const auto marginalMax_size = this->marginalMax_.size();
312 const auto tsize = Size(l_marginalMin_.size());
313
314 while ((i < end_i) || (j < end_j)) {
315 // go through all work indices
316 for (Idx tId = 0; tId < tsize; tId++) {
317 if (l_marginalMin_[tId][i][j] < this->marginalMin_[i][j])
318 this->marginalMin_[i][j] = l_marginalMin_[tId][i][j];
319
320 if (l_marginalMax_[tId][i][j] > this->marginalMax_[i][j])
321 this->marginalMax_[i][j] = l_marginalMax_[tId][i][j];
322 }
323
324 if (++j == domain_size) {
325 j = 0;
326 ++i;
327 if (i < marginalMax_size) domain_size = this->marginalMax_[i].size();
328 }
329 }
330 };
331
332 // launch the threads
334 nb_threads,
335 threadedExec,
336 (nb_threads == 1)
337 ? std::vector< std::pair< NodeId, Idx > >{{0, 0}, {this->marginalMin_.size(), 0}}
338 : this->threadRanges_);
339 }
340
341 /*
342 // old openMP code :
343 #pragma omp parallel
344 {
345 int threadId = threadsOMP::getThreadNumber();
346 long nsize = long(workingSet_[threadId]->size());
347
348 #pragma omp for
349 for (long i = 0; i < nsize; i++) {
350 Size dSize = Size(l_marginalMin_[threadId][i].size());
351
352 for (Size j = 0; j < dSize; j++) {
353 Size tsize = Size(l_marginalMin_.size());
354
355 // go through all threads
356 for (Size tId = 0; tId < tsize; tId++) {
357 if (l_marginalMin_[tId][i][j] < this->marginalMin_[i][j])
358 this->marginalMin_[i][j] = l_marginalMin_[tId][i][j];
359
360 if (l_marginalMax_[tId][i][j] > this->marginalMax_[i][j])
361 this->marginalMax_[i][j] = l_marginalMax_[tId][i][j];
362 } // end of : all threads
363 } // end of : all modalities
364 } // end of : all variables
365 } // end of : parallel region
366 }
367 */
368
369
370 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
372 // compute the number of threads (avoid nested threads)
373 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
374 ? this->threadRanges_.size() - 1
375 : 1; // no nested multithreading
376
377 std::vector< GUM_SCALAR > tEps(nb_threads, 0);
378
379 // create the function to be executed by the threads
380 auto threadedExec = [this, &tEps](const std::size_t this_thread,
381 const std::size_t nb_threads,
382 const std::vector< std::pair< Idx, Idx > >& ranges) {
383 auto& this_tEps = tEps[this_thread];
384 GUM_SCALAR delta = 0;
385
386 auto i = this->threadRanges_[this_thread].first;
387 auto j = this->threadRanges_[this_thread].second;
388 auto domain_size = this->marginalMax_[i].size();
389 const auto end_i = this->threadRanges_[this_thread + 1].first;
390 auto end_j = this->threadRanges_[this_thread + 1].second;
391 const auto marginalMax_size = this->marginalMax_.size();
392
393 while ((i < end_i) || (j < end_j)) {
394 // on min
395 delta = this->marginalMin_[i][j] - this->oldMarginalMin_[i][j];
396 delta = (delta < 0) ? (-delta) : delta;
397 if (this_tEps < delta) this_tEps = delta;
398
399 // on max
400 delta = this->marginalMax_[i][j] - this->oldMarginalMax_[i][j];
401 delta = (delta < 0) ? (-delta) : delta;
402 if (this_tEps < delta) this_tEps = delta;
403
404 this->oldMarginalMin_[i][j] = this->marginalMin_[i][j];
405 this->oldMarginalMax_[i][j] = this->marginalMax_[i][j];
406
407 if (++j == domain_size) {
408 j = 0;
409 ++i;
410 if (i < marginalMax_size) domain_size = this->marginalMax_[i].size();
411 }
412 }
413 };
414
415 // launch the threads
417 nb_threads,
418 threadedExec,
419 (nb_threads == 1)
420 ? std::vector< std::pair< NodeId, Idx > >{{0, 0}, {this->marginalMin_.size(), 0}}
421 : this->threadRanges_);
422
423 // aggregate all the results
424 GUM_SCALAR eps = tEps[0];
425 for (const auto nb: tEps)
426 if (eps < nb) eps = nb;
427
428 return eps;
429 }
430
431 /*
432 // old openMP code :
433 GUM_SCALAR eps = 0;
434 #pragma omp parallel
435 {
436 GUM_SCALAR tEps = 0;
437 GUM_SCALAR delta;
438
439 int tId = threadsOMP::getThreadNumber();
440 long nsize = long(workingSet_[tId]->size());
441
442 #pragma omp for
443 for (long i = 0; i < nsize; i++) {
444 Size dSize = Size(l_marginalMin_[tId][i].size());
445 std::cout << omp_get_num_threads() << std::endl;
446
447 for (Size j = 0; j < dSize; j++) {
448 // on min
449 delta = this->marginalMin_[i][j] - this->oldMarginalMin_[i][j];
450 delta = (delta < 0) ? (-delta) : delta;
451 tEps = (tEps < delta) ? delta : tEps;
452
453 // on max
454 delta = this->marginalMax_[i][j] - this->oldMarginalMax_[i][j];
455 delta = (delta < 0) ? (-delta) : delta;
456 tEps = (tEps < delta) ? delta : tEps;
457
458 this->oldMarginalMin_[i][j] = this->marginalMin_[i][j];
459 this->oldMarginalMax_[i][j] = this->marginalMax_[i][j];
460 }
461 } // end of : all variables
462
463 #pragma omp critical(epsilon_max)
464 {
465 #pragma omp flush(eps)
466 eps = (eps < tEps) ? tEps : eps;
467 }
468
469 } // end of : parallel region
470 return eps;
471 }
472 */
473
474 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
476#pragma omp parallel
477 {
478 int threadId = threadsOMP::getThreadNumber();
479 long nsize = long(workingSet_[threadId]->size());
480
481#pragma omp for
482
483 for (long i = 0; i < nsize; i++) {
484 Size dSize = Size(l_marginalMin_[threadId][i].size());
485
486 for (Size j = 0; j < dSize; j++) {
487 Size tsize = Size(l_marginalMin_.size());
488
489 // go through all threads
490 for (Size tId = 0; tId < tsize; tId++) {
491 if (l_marginalMin_[tId][i][j] < this->oldMarginalMin_[i][j])
492 this->oldMarginalMin_[i][j] = l_marginalMin_[tId][i][j];
493
494 if (l_marginalMax_[tId][i][j] > this->oldMarginalMax_[i][j])
495 this->oldMarginalMax_[i][j] = l_marginalMax_[tId][i][j];
496 } // end of : all threads
497 } // end of : all modalities
498 } // end of : all variables
499 } // end of : parallel region
500 }
501
502 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
504 // don't create threads if there are no vertices saved
505 if (!_infE_::storeVertices_) return;
506
507 // compute the max number of threads to use (avoid nested threads)
508 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
510 : 1; // no nested multithreading
511
512 // create the function to be executed by the threads
513 Size tsize = Size(l_marginalMin_.size());
514 auto threadedExec = [this, tsize](const std::size_t this_thread,
515 const std::size_t nb_threads,
516 Idx work_index,
517 const std::vector< std::pair< Idx, Idx > >& ranges) {
518 for (Idx i = ranges[this_thread].first, end = ranges[this_thread].second; i < end; i++) {
519 // go through all threads
520 for (Size tId = 0; tId < tsize; ++tId) {
521 auto& nodeThreadCredalSet = l_marginalSets_[tId][i];
522
523 // for each vertex, if we are at any opt marginal, add it to the set
524 for (const auto& vtx: nodeThreadCredalSet) {
525 // we run redundancy elimination at each step because there could
526 // be 100000 threads and the set will be so huge...
527 // BUT not if vertices are of dimension 2 ! opt check and equality
528 // should be enough
529 _infE_::updateCredalSets_(i, vtx, (vtx.size() > 2) ? true : false);
530 } // end of : nodeThreadCredalSet
531 } // end of : all threads
532 } // end of : all variables
533 };
534
535 const Size working_size = workingSet_.size();
536 for (Idx work_index = 0; work_index < working_size; ++work_index) {
537 // compute the ranges over which the threads will work
538 const auto nsize = workingSet_[work_index]->size();
539 const auto real_nb_threads = std::min(nb_threads, nsize);
540 const auto ranges = gum::dispatchRangeToThreads(0, nsize, (unsigned int)(real_nb_threads));
541 ThreadExecutor::execute(real_nb_threads, threadedExec, work_index, ranges);
542 }
543 }
544
545 /*
546 // old openMP code :
547 #pragma omp parallel
548 {
549 int threadId = threadsOMP::getThreadNumber();
550 Size nsize = Size(workingSet_[threadId]->size());
551
552 #pragma omp for
553 for (long i = 0; i < long(nsize); i++) {
554 Size tsize = Size(l_marginalMin_.size());
555
556 // go through all threads
557 for (long tId = 0; tId < long(tsize); tId++) {
558 auto& nodeThreadCredalSet = l_marginalSets_[tId][i];
559
560 // for each vertex, if we are at any opt marginal, add it to the set
561 for (const auto& vtx: nodeThreadCredalSet) {
562 // we run redundancy elimination at each step
563 // because there could be 100000 threads and the set will be so
564 // huge
565 // ...
566 // BUT not if vertices are of dimension 2 ! opt check and equality
567 // should be enough
568 _infE_::updateCredalSets_(i, vtx, (vtx.size() > 2) ? true : false);
569 } // end of : nodeThreadCredalSet
570 } // end of : all threads
571 } // end of : all variables
572 } // end of : parallel region
573 }
574 */
575
576
577 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
579 // don't create threads if there are no modalities to compute expectations
580 if (this->modal_.empty()) return;
581
582 // compute the max number of threads to use (avoid nested threads)
583 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
585 : 1; // no nested multithreading
586
587 // we can compute expectations from vertices of the final credal set
589 // create the function to be executed by the threads
590 auto threadedExec = [this](const std::size_t this_thread,
591 const std::size_t nb_threads,
592 Idx work_index,
593 const std::vector< std::pair< Idx, Idx > >& ranges) {
594 for (Idx i = ranges[this_thread].first, end = ranges[this_thread].second; i < end; i++) {
595 std::string var_name = workingSet_[work_index]->variable(i).name();
596 auto delim = var_name.find_first_of("_");
597 var_name = var_name.substr(0, delim);
598
599 if (!l_modal_[work_index].exists(var_name)) continue;
600
601 for (const auto& vertex: _infE_::marginalSets_[i]) {
602 GUM_SCALAR exp = 0;
603 Size vsize = Size(vertex.size());
604
605 for (Size mod = 0; mod < vsize; mod++)
606 exp += vertex[mod] * l_modal_[work_index][var_name][mod];
607
609
611 }
612 }
613 };
614
615 const Size working_size = workingSet_.size();
616 for (Idx work_index = 0; work_index < working_size; ++work_index) {
617 if (!this->l_modal_[work_index].empty()) {
618 // compute the ranges over which the threads will work
619 const auto nsize = workingSet_[work_index]->size();
620 const auto real_nb_threads = std::min(nb_threads, nsize);
621 const auto ranges
622 = gum::dispatchRangeToThreads(0, nsize, (unsigned int)(real_nb_threads));
623 ThreadExecutor::execute(real_nb_threads, threadedExec, work_index, ranges);
624 }
625 }
626
627 return;
628 }
629
630 // create the function to be executed by the threads
631 auto threadedExec = [this](const std::size_t this_thread,
632 const std::size_t nb_threads,
633 Idx work_index,
634 const std::vector< std::pair< Idx, Idx > >& ranges) {
635 for (Idx i = ranges[this_thread].first, end = ranges[this_thread].second; i < end; i++) {
636 std::string var_name = workingSet_[work_index]->variable(i).name();
637 auto delim = var_name.find_first_of("_");
638 var_name = var_name.substr(0, delim);
639
640 if (!l_modal_[work_index].exists(var_name)) continue;
641
642 Size tsize = Size(l_expectationMax_.size());
643
644 for (Idx tId = 0; tId < tsize; tId++) {
645 if (l_expectationMax_[tId][i] > this->expectationMax_[i])
646 this->expectationMax_[i] = l_expectationMax_[tId][i];
647
648 if (l_expectationMin_[tId][i] < this->expectationMin_[i])
649 this->expectationMin_[i] = l_expectationMin_[tId][i];
650 } // end of : each thread
651 } // end of : each variable
652 };
653
654 const Size working_size = workingSet_.size();
655 for (Idx work_index = 0; work_index < working_size; ++work_index) {
656 if (!this->l_modal_[work_index].empty()) {
657 const auto nsize = Size(workingSet_[work_index]->size());
658 const auto real_nb_threads = std::min(nb_threads, nsize);
659 const auto ranges
660 = gum::dispatchRangeToThreads(0, nsize, (unsigned int)(real_nb_threads));
661 ThreadExecutor::execute(real_nb_threads, threadedExec, work_index, ranges);
662 }
663 }
664 }
665
666 /*
667 // old openMP code :
668 // don't create threads if there are no modalities to compute expectations
669 if (this->modal_.empty()) return;
670
671 // we can compute expectations from vertices of the final credal set
672 if (_infE_::storeVertices_) {
673 #pragma omp parallel
674 {
675 int threadId = threadsOMP::getThreadNumber();
676
677 if (!this->l_modal_[threadId].empty()) {
678 Size nsize = Size(workingSet_[threadId]->size());
679
680 #pragma omp for
681 for (long i = 0; i < long(nsize); i++) { // i needs to be signed (due to omp with
682 // visual c++ 15)
683 std::string var_name = workingSet_[threadId]->variable(i).name();
684 auto delim = var_name.find_first_of("_");
685 var_name = var_name.substr(0, delim);
686
687 if (!l_modal_[threadId].exists(var_name)) continue;
688
689 for (const auto& vertex: _infE_::marginalSets_[i]) {
690 GUM_SCALAR exp = 0;
691 Size vsize = Size(vertex.size());
692
693 for (Size mod = 0; mod < vsize; mod++)
694 exp += vertex[mod] * l_modal_[threadId][var_name][mod];
695
696 if (exp > _infE_::expectationMax_[i]) _infE_::expectationMax_[i] = exp;
697
698 if (exp < _infE_::expectationMin_[i]) _infE_::expectationMin_[i] = exp;
699 }
700 } // end of : each variable parallel for
701 } // end of : if this thread has modals
702 } // end of parallel region
703 return;
704 }
705
706 #pragma omp parallel
707 {
708 int threadId = threadsOMP::getThreadNumber();
709
710 if (!this->l_modal_[threadId].empty()) {
711 Size nsize = Size(workingSet_[threadId]->size());
712 #pragma omp for
713 for (long i = 0; i < long(nsize);
714 i++) { // long instead of Idx due to omp for visual C++15
715 std::string var_name = workingSet_[threadId]->variable(i).name();
716 auto delim = var_name.find_first_of("_");
717 var_name = var_name.substr(0, delim);
718
719 if (!l_modal_[threadId].exists(var_name)) continue;
720
721 Size tsize = Size(l_expectationMax_.size());
722
723 for (Idx tId = 0; tId < tsize; tId++) {
724 if (l_expectationMax_[tId][i] > this->expectationMax_[i])
725 this->expectationMax_[i] = l_expectationMax_[tId][i];
726
727 if (l_expectationMin_[tId][i] < this->expectationMin_[i])
728 this->expectationMin_[i] = l_expectationMin_[tId][i];
729 } // end of : each thread
730 } // end of : each variable
731 } // end of : if modals not empty
732 } // end of : parallel region
733 }
734 */
735
736 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
738 using dBN = std::vector< bool >;
739
740 Size nsize = Size(workingSet_[0]->size());
741
742 // no parallel insert in hash-tables (OptBN)
743 for (Idx i = 0; i < nsize; i++) {
744 // we don't store anything for observed variables
745 if (_infE_::evidence_.exists(i)) continue;
746
747 Size dSize = Size(l_marginalMin_[0][i].size());
748
749 for (Size j = 0; j < dSize; j++) {
750 // go through all threads
751 std::vector< Size > keymin(3);
752 keymin[0] = i;
753 keymin[1] = j;
754 keymin[2] = 0;
755 std::vector< Size > keymax(keymin);
756 keymax[2] = 1;
757
758 Size tsize = Size(l_marginalMin_.size());
759
760 for (Size tId = 0; tId < tsize; tId++) {
761 if (l_marginalMin_[tId][i][j] == this->marginalMin_[i][j]) {
762 const std::vector< dBN* >& tOpts = l_optimalNet_[tId]->getBNOptsFromKey(keymin);
763 Size osize = Size(tOpts.size());
764
765 for (Size bn = 0; bn < osize; bn++) {
766 _infE_::dbnOpt_.insert(*tOpts[bn], keymin);
767 }
768 }
769
770 if (l_marginalMax_[tId][i][j] == this->marginalMax_[i][j]) {
771 const std::vector< dBN* >& tOpts = l_optimalNet_[tId]->getBNOptsFromKey(keymax);
772 Size osize = Size(tOpts.size());
773
774 for (Size bn = 0; bn < osize; bn++) {
775 _infE_::dbnOpt_.insert(*tOpts[bn], keymax);
776 }
777 }
778 } // end of : all threads
779 } // end of : all modalities
780 } // end of : all variables
781 }
782
783 template < GUM_Numeric GUM_SCALAR, class BNInferenceEngine >
786 Size tsize = Size(workingSet_.size());
787
788 // delete pointers
789 for (Size bn = 0; bn < tsize; bn++) {
791
792 if (workingSet_[bn] != nullptr) delete workingSet_[bn];
793
795 if (l_inferenceEngine_[bn] != nullptr) delete l_optimalNet_[bn];
796
797 if (this->workingSetE_[bn] != nullptr) {
798 for (const auto ev: *workingSetE_[bn])
799 delete ev;
800
801 delete workingSetE_[bn];
802 }
803
804 if (l_inferenceEngine_[bn] != nullptr) delete l_inferenceEngine_[bn];
805 }
806
807 // this is important, those will be resized with the correct number of
808 // threads.
809
810 workingSet_.clear();
811 workingSetE_.clear();
812 l_inferenceEngine_.clear();
813 l_optimalNet_.clear();
814
815 l_marginalMin_.clear();
816 l_marginalMax_.clear();
817 l_expectationMin_.clear();
818 l_expectationMax_.clear();
819 l_modal_.clear();
820 l_marginalSets_.clear();
821 l_evidence_.clear();
822 l_clusters_.clear();
823 }
824
825 } // namespace credal
826} // namespace gum
double epsilon() const override
Returns the value of epsilon.
double epsilonStandard() const noexcept
Size getNumberOfThreads() const override
returns the current max number of threads used by the class containing this ThreadNumberManager
Class template representing a Credal Network.
Definition credalNet.h:101
margi oldMarginalMax_
Old upper marginals used to compute epsilon.
margi evidence_
Holds observed variables states.
bool storeBNOpt_
Iterations limit stopping rule used by some algorithms such as CNMonteCarloSampling.
margi marginalMax_
Upper marginals.
void updateCredalSets_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
Given a node id and one of it's possible vertex, update it's credal set.
InferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Construtor.
margi oldMarginalMin_
Old lower marginals used to compute epsilon.
bool storeVertices_
True if credal sets vertices are stored, False otherwise.
virtual void eraseAllEvidence()
removes all the evidence entered into the network
expe expectationMax_
Upper expectations, if some variables modalities were inserted.
credalSet marginalSets_
Credal sets vertices, if enabled.
const CredalNet< GUM_SCALAR > & credalNet() const
Get this credal network.
margi marginalMin_
Lower marginals.
dynExpe modal_
Variables modalities used to compute expectations.
expe expectationMin_
Lower expectations, if some variables modalities were inserted.
std::vector< std::pair< NodeId, Idx > > threadRanges_
the ranges of elements of marginalMin_ and marginalMax_ processed by each thread
VarMod2BNsMap< GUM_SCALAR > dbnOpt_
Object used to efficiently store optimal bayes net during inference, for some algorithms.
Class template acting as a wrapper for Lexicographic Reverse Search by David Avis.
Definition LrsWrapper.h:121
const matrix & getOutput() const
Get the output matrix solution of the problem.
void setUpV(const Size &card, const Size &vertices)
Sets up a V-representation.
void elimRedundVrep()
V-Redundancy elimination.
void fillV(const std::vector< GUM_SCALAR > &vertex)
Creates the V-representation of a polytope by adding a vertex to the problem input _input_.
void updateMarginals_()
Fusion of threads marginals.
_margis_ l_marginalMin_
Threads lower marginals, one per thread.
_expes_ l_expectationMax_
Threads upper expectations, one per thread.
_expes_ l_expectationMin_
Threads lower expectations, one per thread.
std::vector< _bnet_ * > workingSet_
Threads IBayesNet.
std::vector< BNInferenceEngine * > l_inferenceEngine_
Threads BNInferenceEngine.
_credalSets_ l_marginalSets_
Threads vertices.
void optFusion_()
Fusion of threads optimal IBayesNet.
std::vector< VarMod2BNsMap< GUM_SCALAR > * > l_optimalNet_
Threads optimal IBayesNet.
void eraseAllEvidence() override
Erase all inference related data to perform another one.
void updateOldMarginals_()
Update old marginals (from current marginals).
_margis_ l_marginalMax_
Threads upper marginals, one per thread.
MultipleInferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Constructor.
void expFusion_()
Fusion of threads expectations.
void initThreadsData_(const Size &num_threads, const bool _storeVertices_, const bool _storeBNOpt_)
Initialize threads data.
bool updateThread_(Size this_thread, const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
Update thread information (marginals, expectations, IBayesNet, vertices) for a given node id.
std::vector< List< const Tensor< GUM_SCALAR > * > * > workingSetE_
Threads evidence.
void _updateThreadCredalSets_(Size this_thread, const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund)
const GUM_SCALAR computeEpsilon_() override
Compute epsilon and update old marginals.
Typed, documented, sectioned configuration singleton read from an .ini content.
unsigned int getThreadNumber()
Get the calling thread id.
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
Size NodeId
Type for node ids.
GUM_SHARED_PUBLIC unsigned int currentRandomGeneratorValue()
returns the current generator's value
Abstract class representing CredalNet inference engines.
Abstract class representing CredalNet inference engines.
namespace for all credal networks entities
Definition agrum.h:61
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
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
Definition threads.cpp:76
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
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