aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
tensor_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
49
50#include <algorithm>
51
52#include <agrum/agrum.h>
53
56
58
59namespace gum {
60 // Default constructor: creates an empty null dimensional matrix
61 // choose a MultiDimArray<> as decorated implementation
62 template < GUM_Numeric GUM_SCALAR >
64 MultiDimDecorator< GUM_SCALAR >(new MultiDimArray< GUM_SCALAR >(), GUM_SCALAR(1)) {
65 GUM_CONSTRUCTOR(Tensor)
66 }
67
68 // Default constructor: creates an empty null dimensional matrix
69 // choose a MultiDimArray<> as decorated implementation
70 template < GUM_Numeric GUM_SCALAR >
71 Tensor< GUM_SCALAR >::Tensor(const std::vector< const DiscreteVariable* >& vars) : Tensor() {
72 for (const auto& var: vars) {
73 this->add(*var);
74 }
75 }
76
77 // constructor using aContent as content
78 template < GUM_Numeric GUM_SCALAR >
80 MultiDimDecorator< GUM_SCALAR >(aContent, GUM_SCALAR(1)) {
81 // for debugging purposes
82 GUM_CONSTRUCTOR(Tensor)
83 }
84
85 // copy constructor
86 template < GUM_Numeric GUM_SCALAR >
87 Tensor< GUM_SCALAR >::Tensor(const Tensor< GUM_SCALAR >& src) :
88 Tensor< GUM_SCALAR >(
89 static_cast< MultiDimImplementation< GUM_SCALAR >* >(src.content()->newFactory()),
90 *(src.content())) {
91 this->empty_value_ = src.empty_value_;
92 // GUM_CONS_CPY not here because in called Tensor
93 // GUM_CONS_CPY( Tensor );
94 }
95
97 template < GUM_Numeric GUM_SCALAR >
98 Tensor< GUM_SCALAR >::Tensor(Tensor< GUM_SCALAR >&& from) :
99 MultiDimDecorator< GUM_SCALAR >(std::forward< MultiDimDecorator< GUM_SCALAR > >(from)) {
100 GUM_CONS_MOV(Tensor)
101 }
103 // complex copy constructor : we choose the implementation
104 template < GUM_Numeric GUM_SCALAR >
107 MultiDimDecorator< GUM_SCALAR >(aContent) {
108 // for debugging purposes
109 GUM_CONSTRUCTOR(Tensor)
110
111 if (!src.empty()) {
112 this->beginMultipleChanges();
113
114 for (Idx i = 0; i < src.variablesSequence().size(); i++) {
115 this->add(*(src.variablesSequence()[i]));
116 }
117
118 this->endMultipleChanges();
119 this->content()->copyFrom(*src.content());
120 }
121 }
122
123 // operator= (copy)
124 template < GUM_Numeric GUM_SCALAR >
125 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator=(const Tensor< GUM_SCALAR >& src) {
126 GUM_OP_CPY(Tensor)
127 if (&src == this) return *this;
129 return *this;
130 }
131
132 // operator= (move)
133 template < GUM_Numeric GUM_SCALAR >
134 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator=(Tensor< GUM_SCALAR >&& src) {
135 GUM_OP_MOV(Tensor)
136 if (&src == this) return *this;
138 std::forward< MultiDimDecorator< GUM_SCALAR > >(src));
139 return *this;
140 }
141
142 // destructor
143
144 template < GUM_Numeric GUM_SCALAR >
146 // for debugging purposes
147 GUM_DESTRUCTOR(Tensor)
148 }
149
150 template < GUM_Numeric GUM_SCALAR >
151 Tensor< GUM_SCALAR >* Tensor< GUM_SCALAR >::newFactory() const {
152 return new Tensor< GUM_SCALAR >(
153 static_cast< MultiDimImplementation< GUM_SCALAR >* >(this->content()->newFactory()));
155
156 // sum of all elements in this
157 template < GUM_Numeric GUM_SCALAR >
158 GUM_SCALAR Tensor< GUM_SCALAR >::sum() const {
159 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
160 return this->empty_value_;
161 }
162 return gum::projectSum(*this->content());
163 }
164
165 // product of all elements in this
166 template < GUM_Numeric GUM_SCALAR >
167 GUM_SCALAR Tensor< GUM_SCALAR >::product() const {
168 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
169 return this->empty_value_;
170 }
171 return gum::projectProduct(*this->content());
172 }
174 // max of all elements in this
175 template < GUM_Numeric GUM_SCALAR >
176 GUM_SCALAR Tensor< GUM_SCALAR >::max() const {
177 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
178 return this->empty_value_;
179 }
180 return gum::projectMax(*this->content());
181 }
182
183 // min of all elements in this
184 template < GUM_Numeric GUM_SCALAR >
185 GUM_SCALAR Tensor< GUM_SCALAR >::min() const {
186 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
187 return this->empty_value_;
188 }
189 return gum::projectMin(*this->content());
190 }
191
192 // max of all non-one elements in this
193 // warning can return 1 if no other value than 1 ...
194 template < GUM_Numeric GUM_SCALAR >
196 GUM_SCALAR res;
197
198 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
199 res = this->empty_value_;
200 } else {
201 res = this->reduce(
202 [](GUM_SCALAR z, GUM_SCALAR p) {
203 return (p == static_cast< GUM_SCALAR >(1)) ? z
204 : (z == static_cast< GUM_SCALAR >(1)) ? p
205 : (p > z ? p : z);
206 },
207 static_cast< GUM_SCALAR >(1));
209
210 return res;
211 }
212
213 // min of all non-zero elements in this
214 // warning can return 0 if no other value than 0 ...
215 template < GUM_Numeric GUM_SCALAR >
217 GUM_SCALAR res;
218
219 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
220 res = this->empty_value_;
221 } else {
222 res = this->reduce(
223 [](GUM_SCALAR z, GUM_SCALAR p) {
224 return (p == static_cast< GUM_SCALAR >(0)) ? z
225 : (z == static_cast< GUM_SCALAR >(0)) ? p
226 : (p < z ? p : z);
227 },
228 static_cast< GUM_SCALAR >(0));
230 return res;
231 }
232
233 template < GUM_Numeric GUM_SCALAR >
235 std::function< GUM_SCALAR(const gum::Instantiation&) > f) const {
236 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
237 return static_cast< GUM_SCALAR >(0);
238 }
240 GUM_SCALAR res = 0;
241 auto i = Instantiation(*this);
242 for (i.setFirst(); !i.end(); i.inc()) {
243 const GUM_SCALAR v_f = f(i);
244 if (v_f != GUM_SCALAR(0.0)) { res += this->get(i) * v_f; }
245 }
246 return res;
247 }
248
249 template < GUM_Numeric GUM_SCALAR >
250 GUM_SCALAR Tensor< GUM_SCALAR >::mean() const {
251 if (this->nbrDim() != 1) { GUM_ERROR(ArgumentError, "The tensor is not a marginal"); }
252 if (!gum::isCloseToOne(sum())) { GUM_ERROR(ArgumentError, "The tensor is not a distribution"); }
253 if (this->variable(0).isNumerical()) {
254 return expectedValue([this](const gum::Instantiation& i) -> GUM_SCALAR {
255 return GUM_SCALAR(this->variable(0).numerical(i.val(0)));
256 });
257 } else {
258 GUM_ERROR(ArgumentError, "The variable is not numerical");
259 }
260 }
261
262 template < GUM_Numeric GUM_SCALAR >
264 if (this->nbrDim() != 1) { GUM_ERROR(ArgumentError, "The tensor is not a marginal"); }
265 if (!gum::isCloseToOne(sum())) { GUM_ERROR(ArgumentError, "The tensor is not a distribution"); }
266 if (this->variable(0).isNumerical()) {
267 const auto mu = mean();
268 return expectedValue([this, mu](const gum::Instantiation& i) -> GUM_SCALAR {
269 const auto r = GUM_SCALAR(this->variable(0).numerical(i.val(0))) - mu;
270 return r * r;
271 });
272 } else {
273 GUM_ERROR(ArgumentError, "The variable is not numerical");
274 }
275 }
276
277 template < GUM_Numeric GUM_SCALAR >
278 GUM_SCALAR Tensor< GUM_SCALAR >::stdDev() const {
279 return std::sqrt(variance());
280 }
281
282 // entropy of this
283 template < GUM_Numeric GUM_SCALAR >
284 GUM_SCALAR Tensor< GUM_SCALAR >::entropy() const {
285 return -this->expectedValue([this](const gum::Instantiation& i) -> GUM_SCALAR {
286 return GUM_SCALAR(GUM_LOG2_OR_0(this->get(i)));
287 });
288 }
289
290 template < GUM_Numeric GUM_SCALAR >
291 const Tensor< GUM_SCALAR >&
292 Tensor< GUM_SCALAR >::fillWith(const std::vector< GUM_SCALAR >& data) const {
293 this->populate(data);
294 return *this;
295 }
296
297 template < GUM_Numeric GUM_SCALAR >
298 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::fillWith(const GUM_SCALAR& val) const {
299 this->fill(val);
300 return *this;
301 }
302
303 template < GUM_Numeric GUM_SCALAR >
304 const Tensor< GUM_SCALAR >&
305 Tensor< GUM_SCALAR >::fillWith(const Tensor< GUM_SCALAR >& src) const {
306 if (src.domainSize() != this->domainSize()) {
307 GUM_ERROR(InvalidArgument, "Tensor to copy has not the same domainSize.")
308 }
309 gum::Set< std::string > son; // set of names
310 for (const auto& v: src.variablesSequence()) {
311 son.insert(v->name());
312 }
313 for (const auto& v: this->variablesSequence()) {
314 if (!son.contains(v->name())) {
316 "Variable <" << v->name() << "> not present in src (" << son << ").")
317 }
318 // we check size, labels and order of labels in the same time
319 if (v->toString() != src.variable(v->name()).toString()) {
320 GUM_ERROR(InvalidArgument, "Variables <" << v->name() << "> are not identical.")
321 }
322 }
323
324 Instantiation Isrc(src);
325 Instantiation Idst(*this);
326
327 // pre-compute index mapping from src variable positions to dst positions (O(N))
328 // avoids repeated name lookups (O(N) each) inside the hot loop
329 const Idx ndim = src.nbrDim();
330 std::vector< Idx > src_to_dst(ndim);
331 for (Idx i = 0; i < ndim; i++) {
332 src_to_dst[i] = Idst.pos(this->variable(Isrc.variable(i).name()));
333 }
334
335 for (Isrc.setFirst(); !Isrc.end(); ++Isrc) {
336 for (Idx i = 0; i < ndim; i++) {
337 Idst.chgVal(src_to_dst[i], Isrc.val(i));
338 }
339 this->set(Idst, src.get(Isrc));
340 }
341
342 return *this;
343 }
344
345 template < GUM_Numeric GUM_SCALAR >
347 Tensor< GUM_SCALAR >::fillWith(const Tensor< GUM_SCALAR >& src,
348 const std::vector< std::string >& mapSrc) const {
349 if (src.nbrDim() != this->nbrDim()) {
350 GUM_ERROR(InvalidArgument, "Tensor to copy has not the same size.")
351 }
352 if (src.nbrDim() != mapSrc.size()) {
353 GUM_ERROR(InvalidArgument, "Tensor and vector have not the same size.")
354 }
355 Instantiation Isrc;
356 for (Idx i = 0; i < src.nbrDim(); i++) {
357 if (src.variable(mapSrc[i]).domainSize() != this->variable(i).domainSize()) {
359 "Variables " << mapSrc[i] << " (in the argument) and " << this->variable(i).name()
360 << " have not the same dimension.")
361 } else {
362 Isrc.add(src.variable(mapSrc[i]));
363 }
364 }
365 Instantiation Idst(*this);
366 for (Isrc.setFirst(); !Isrc.end(); ++Isrc, ++Idst) {
367 this->set(Idst, src.get(Isrc));
368 }
369
370 return *this;
371 }
372
373 template < GUM_Numeric GUM_SCALAR >
374 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::sq() const {
375 this->apply([](GUM_SCALAR x) { return x * x; });
376 return *this;
377 }
379 template < GUM_Numeric GUM_SCALAR >
380 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::log2() const {
381 this->apply([](GUM_SCALAR x) { return std::log2(x); });
382 return *this;
384
385 template < GUM_Numeric GUM_SCALAR >
386 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::sgn() const {
387 this->apply([](GUM_SCALAR x) { return (GUM_SCALAR(0) < x) - (x < GUM_SCALAR(0)); });
388 return *this;
389 }
391 template < GUM_Numeric GUM_SCALAR >
392 GUM_SCALAR Tensor< GUM_SCALAR >::KL(const Tensor< GUM_SCALAR >& p) const {
393 if (this->nbrDim() != p.nbrDim())
394 GUM_ERROR(InvalidArgument, "BNdistance between tensors with different numbers of dimensions")
395 for (const auto var: p.variablesSequence()) {
396 if (!this->contains(*var))
397 GUM_ERROR(InvalidArgument, "A variable in the argument does not belong to the tensor.")
398 }
399 for (const auto var: this->variablesSequence()) {
400 if (!p.contains(*var))
401 GUM_ERROR(InvalidArgument, "A variable does not belong to the argument.")
403
404 Instantiation inst(*this);
405 auto res = static_cast< GUM_SCALAR >(0);
406 for (inst.setFirst(); !inst.end(); inst.inc()) {
407 GUM_SCALAR x = this->get(inst);
408 GUM_SCALAR y = p.get(inst);
409 if (static_cast< GUM_SCALAR >(0) == x) // 0*log(0/y)=0
410 continue;
411
412 if (static_cast< GUM_SCALAR >(0) == y)
413 // we know that x!=0;
414 GUM_ERROR(FatalError, "The argument has a 0 at " << inst << " while the tensor has not.")
416 res += x * std::log2(x / y);
417 }
418 return res;
419 }
420
421 template < GUM_Numeric GUM_SCALAR >
422 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::abs() const {
423 this->apply([](GUM_SCALAR x) {
424 if (x >= 0) return x;
425 else return -x;
426 });
427 return *this;
428 }
429
430 // normalisation of this
431 // do nothing is sum is 0
432 template < GUM_Numeric GUM_SCALAR >
433 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::normalize() const {
434 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
435 if (this->empty_value_ != static_cast< GUM_SCALAR >(0))
436 this->empty_value_ = static_cast< GUM_SCALAR >(1.0);
437 } else {
438 GUM_SCALAR s = sum();
439
440 if (s != (GUM_SCALAR)0) {
441 this->apply([s](GUM_SCALAR x) { return x / s; });
442 }
443 }
444 return *this;
446
447 template < GUM_Numeric GUM_SCALAR >
448 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::normalizeAsCPT(const Idx& varId) const {
449 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
450 if (this->empty_value_ != static_cast< GUM_SCALAR >(0)) {
451 this->empty_value_ = static_cast< GUM_SCALAR >(1.0);
452 } else {
453 GUM_ERROR(FatalError, "Normalization for a tensor that sum to 0 in " << *this)
454 }
455 } else {
456 if (varId >= this->nbrDim()) {
457 GUM_ERROR(FatalError, varId << " is not a position for " << *this)
458 }
459 Instantiation inst(*this);
460 const auto& v = this->variable(varId);
461
462 for (inst.setFirst(); !inst.end(); inst.incNotVar(v)) {
463 auto s = (GUM_SCALAR)0.0;
464 for (inst.setFirstVar(v); !inst.end(); inst.incVar(v))
465 s += this->get(inst);
466 if (s == (GUM_SCALAR)0.0) {
467 GUM_ERROR(FatalError, "Normalization for a tensor that sum to 0 in " << *this)
468 }
469 if (s != (GUM_SCALAR)1.0) {
470 for (inst.setFirstVar(v); !inst.end(); inst.incVar(v))
471 this->set(inst, this->get(inst) / s);
472 }
473 inst.setFirstVar(v); // to remove inst.end()
475 }
476 return *this;
477 }
479 template < GUM_Numeric GUM_SCALAR >
480 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::scale(GUM_SCALAR v) const {
481 this->apply([v](GUM_SCALAR x) { return x * v; });
482 return *this;
483 }
485 template < GUM_Numeric GUM_SCALAR >
486 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::translate(GUM_SCALAR v) const {
487 this->apply([v](GUM_SCALAR x) { return x + v; });
488 return *this;
489 }
490
491 template < GUM_Numeric GUM_SCALAR >
492 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::inverse() const {
493 this->apply([](GUM_SCALAR x) { return 1 / x; });
494 return *this;
496
497 template < GUM_Numeric GUM_SCALAR >
498 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::sumOut(const gum::VariableSet& del_vars) const {
499 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
500 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
502
503 // if we remove all the variables, create an empty tensor
504 // TODO: remove this test when operations will be able to handle empty tensors
505 if (this->variablesSequence().size() <= del_vars.size()) {
506 bool equal = true;
507 for (const auto var: this->variablesSequence()) {
508 if (!del_vars.exists(var)) {
509 equal = false;
510 break;
511 }
512 }
513 if (equal) { return Tensor< GUM_SCALAR >().fillWith(this->sum()); }
514 }
515
516 return Tensor< GUM_SCALAR >(gum::projectSum(*this->content(), del_vars));
517 }
518
519 template < GUM_Numeric GUM_SCALAR >
520 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::prodOut(const gum::VariableSet& del_vars) const {
521 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
522 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
523 }
524
525 // if we remove all the variables, create an empty tensor
526 // TODO: remove this test when operations will be able to handle empty tensors
527 if (this->variablesSequence().size() <= del_vars.size()) {
528 bool equal = true;
529 for (const auto var: this->variablesSequence()) {
530 if (!del_vars.exists(var)) {
531 equal = false;
532 break;
533 }
534 }
535 if (equal) { return Tensor< GUM_SCALAR >().fillWith(this->product()); }
536 }
537
538 return Tensor< GUM_SCALAR >(gum::projectProduct(*this->content(), del_vars));
539 }
540
541 template < GUM_Numeric GUM_SCALAR >
542 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::minOut(const gum::VariableSet& del_vars) const {
543 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
544 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
545 }
546
547 // if we remove all the variables, create an empty tensor
548 // TODO: remove this test when operations will be able to handle empty tensors
549 if (this->variablesSequence().size() <= del_vars.size()) {
550 bool equal = true;
551 for (const auto var: this->variablesSequence()) {
552 if (!del_vars.exists(var)) {
553 equal = false;
554 break;
555 }
556 }
557 if (equal) { return Tensor< GUM_SCALAR >().fillWith(this->min()); }
558 }
559
560 return Tensor< GUM_SCALAR >(gum::projectMin(*this->content(), del_vars));
561 }
562
563 template < GUM_Numeric GUM_SCALAR >
564 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::maxOut(const gum::VariableSet& del_vars) const {
565 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
566 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
567 }
568
569 // if we remove all the variables, create an empty tensor
570 // TODO: remove this test when operations will be able to handle empty tensors
571 if (this->variablesSequence().size() <= del_vars.size()) {
572 bool equal = true;
573 for (const auto var: this->variablesSequence()) {
574 if (!del_vars.exists(var)) {
575 equal = false;
576 break;
577 }
578 }
579 if (equal) { return Tensor< GUM_SCALAR >().fillWith(this->max()); }
580 }
581
582 return Tensor< GUM_SCALAR >(gum::projectMax(*this->content(), del_vars));
583 }
584
585 template < GUM_Numeric GUM_SCALAR >
586 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::sumIn(const gum::VariableSet& kept_vars) const {
587 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
588 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
589 }
590
591 // if kept_var is empty, create an empty tensor
592 // TODO: remove this test when operations will be able to handle empty tensors
593 if (kept_vars.empty()) { return Tensor< GUM_SCALAR >().fillWith(this->sum()); }
594
595 return Tensor< GUM_SCALAR >(gum::projectSum(*this->content(), _complementVars_(kept_vars)));
596 }
597
598 template < GUM_Numeric GUM_SCALAR >
599 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::prodIn(const gum::VariableSet& kept_vars) const {
600 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
601 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
602 }
603
604 // if kept_var is empty, create an empty tensor
605 // TODO: remove this test when operations will be able to handle empty tensors
606 if (kept_vars.empty()) { return Tensor< GUM_SCALAR >().fillWith(this->product()); }
607
608 return Tensor< GUM_SCALAR >(gum::projectProduct(*this->content(), _complementVars_(kept_vars)));
609 }
610
611 template < GUM_Numeric GUM_SCALAR >
612 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::minIn(const gum::VariableSet& kept_vars) const {
613 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
614 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
615 }
616
617 // if kept_var is empty, create an empty tensor
618 // TODO: remove this test when operations will be able to handle empty tensors
619 if (kept_vars.empty()) { return Tensor< GUM_SCALAR >().fillWith(this->min()); }
620
621 return Tensor< GUM_SCALAR >(gum::projectMin(*this->content(), _complementVars_(kept_vars)));
622 }
623
624 template < GUM_Numeric GUM_SCALAR >
625 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::maxIn(const gum::VariableSet& kept_vars) const {
626 if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) {
627 return Tensor< GUM_SCALAR >().fillWith(this->empty_value_);
628 }
629
630 // if kept_var is empty, create an empty tensor
631 // TODO: remove this test when operations will be able to handle empty tensors
632 if (kept_vars.empty()) { return Tensor< GUM_SCALAR >().fillWith(this->max()); }
633
634 return Tensor< GUM_SCALAR >(gum::projectMax(*this->content(), _complementVars_(kept_vars)));
635 }
636
637 template < GUM_Numeric GUM_SCALAR >
638 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::isNonZeroMap() const {
639 auto p = Tensor< GUM_SCALAR >(*this);
640 p.apply([](GUM_SCALAR x) {
641 if (x != static_cast< GUM_SCALAR >(0)) return static_cast< GUM_SCALAR >(1);
642 else return static_cast< GUM_SCALAR >(0);
643 });
644 return p;
645 }
646
647 template < GUM_Numeric GUM_SCALAR >
649 gum::VariableSet cplt;
650
651 for (const auto x: this->variablesSequence())
652 if (!vars.contains(x)) cplt.insert(x);
653
654 return cplt;
655 }
656
657 template < GUM_Numeric GUM_SCALAR >
658 Tensor< GUM_SCALAR >
659 Tensor< GUM_SCALAR >::reorganize(const std::vector< const DiscreteVariable* >& vars) const {
660 if (vars.size() != this->nbrDim())
662 "The argument contains " << vars.size() << " variables instead of "
663 << this->nbrDim() << ".")
664 for (const auto var: vars) {
665 if (!this->contains(*var))
666 GUM_ERROR(InvalidArgument, "A variable in the argument does not belong to the tensor.")
667 }
668
669 Tensor< GUM_SCALAR > p;
670 p.beginMultipleChanges();
671 for (const auto var: vars)
672 p.add(*var);
673 p.endMultipleChanges();
674 p.copyFrom(*this, nullptr); // copy *this in p using the same order
675
676 return p;
677 }
678
679 template < GUM_Numeric GUM_SCALAR >
680 Tensor< GUM_SCALAR >
681 Tensor< GUM_SCALAR >::reorganize(const std::vector< std::string >& vars) const {
682 std::vector< const DiscreteVariable* > res;
683
685 for (gum::Idx i = 0; i < this->nbrDim(); i++)
686 namesToVars.insert(this->variable(i).name(), &(this->variable(i)));
687
688 for (const auto& name: vars) {
689 if (!namesToVars.exists(name)) {
690 GUM_ERROR(gum::InvalidArgument,
691 "'" << name << "' is a not a name of a variable in this tensor")
692 }
693 res.push_back(namesToVars[name]);
694 }
695 return reorganize(res);
696 }
697
698 template < GUM_Numeric GUM_SCALAR >
699 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::putFirst(const DiscreteVariable* var) const {
700 if (!this->contains(*var)) {
701 GUM_ERROR(InvalidArgument, "The variable to put first does not belong to the tensor")
702 }
703 if (&(this->variable(0)) == var) return Tensor< GUM_SCALAR >(*this);
704
705 std::vector< const DiscreteVariable* > vars;
706 vars.push_back(var);
707 for (Idx i = 0; i < this->nbrDim(); i++)
708 if (&(this->variable(i)) != var) vars.push_back(&(this->variable(i)));
709
710 return this->reorganize(vars);
711 }
712
713 template < GUM_Numeric GUM_SCALAR >
714 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::putFirst(std::string_view varname) const {
715 const DiscreteVariable* var = nullptr;
716
717 for (gum::Idx i = 0; i < this->nbrDim(); i++)
718 if (this->variable(i).name() == varname) {
719 var = &(this->variable(i));
720 break;
721 }
722 if (var == nullptr)
724 "The variable '" << varname << "' to put first does not belong to the tensor")
725 return this->putFirst(var);
726 }
727
728 template < GUM_Numeric GUM_SCALAR >
729 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::extract(const Instantiation& inst) const {
730 Tensor< GUM_SCALAR > p;
731 p.extractFrom(*this, inst);
732
733 return p;
734 }
735
736 template < GUM_Numeric GUM_SCALAR >
738 if (this->nbrDim() != 1) {
739 GUM_ERROR(FatalError, "To draw from a tensor, the dimension must be 1")
740 }
741
742 auto r = static_cast< GUM_SCALAR >(randomProba());
743 Instantiation Ip(*this);
744 for (Ip.setFirst(); !Ip.end(); Ip.inc()) {
745 r -= this->get(Ip);
746 if (r <= 0) return Ip.val(0);
747 }
748 return this->variable(0).domainSize() - 1;
749 }
750
751 template < GUM_Numeric GUM_SCALAR >
752 std::ostream& operator<<(std::ostream& out, const Tensor< GUM_SCALAR >& array) {
753 out << array.toString();
754 return out;
755 }
756
757 // argmax of all elements in this
758 template < GUM_Numeric GUM_SCALAR >
760 Instantiation I(*this);
762
763 // if (static_cast< MultiDimContainer< GUM_SCALAR >* >(this->content_)->empty()) { return
764 // res; }
765 for (I.setFirst(); !I.end(); ++I) {
766 if (this->get(I) == v) res.insert(Instantiation(I, false));
767 }
768 return res;
769 }
770
771 // argmax of all elements in this
772 template < GUM_Numeric GUM_SCALAR >
773 std::pair< Set< Instantiation >, GUM_SCALAR > Tensor< GUM_SCALAR >::argmax() const {
774 auto m = max();
775 return std::pair(findAll(m), m);
776 }
777
778 // argmin of all elements in this
779 template < GUM_Numeric GUM_SCALAR >
780 std::pair< Set< Instantiation >, GUM_SCALAR > Tensor< GUM_SCALAR >::argmin() const {
781 auto m = min();
782 return std::pair(findAll(m), m);
783 }
784
785 template < GUM_Numeric GUM_SCALAR >
786 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::random() const {
787 if (this->domainSize() == 0) return *this;
788
789 std::vector< GUM_SCALAR > v;
790 v.reserve(this->domainSize());
791 for (Size i = 0; i < this->domainSize(); ++i) {
792 auto r = (GUM_SCALAR)randomProba();
793 v.push_back(r);
794 }
795 this->fillWith(v);
796 return *this;
797 }
798
799 template < GUM_Numeric GUM_SCALAR >
800 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::randomDistribution() const {
801 if (this->domainSize() == 0) {
802 this->fillWith((GUM_SCALAR)1.0);
803 } else {
805 }
806
807 return *this;
808 }
809
810 template < GUM_Numeric GUM_SCALAR >
811 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::randomCPT() const {
812 if (this->domainSize() == 0) {
813 this->fillWith((GUM_SCALAR)1.0);
814 } else {
815 gum::Instantiation I(*this);
816 const auto& v = this->variable(0);
817 for (I.setFirstNotVar(v); !I.end(); I.incNotVar(v)) {
818 const auto& distrib = gum::randomDistribution< GUM_SCALAR >(v.domainSize());
819 for (I.setFirstVar(v); !I.end(); I.incVar(v)) {
820 this->set(I, distrib[I.val(0)]);
821 }
822 I.unsetEnd();
823 }
824 }
825 return *this;
826 }
827
828 template < GUM_Numeric GUM_SCALAR >
829 const Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::noising(GUM_SCALAR alpha) const {
830 if ((alpha < GUM_SCALAR(0.0)) || (alpha > GUM_SCALAR(1.0))) {
831 GUM_ERROR(InvalidArgument, "alpha must be in [0,1]")
832 }
833 Tensor< GUM_SCALAR > noise(*this);
834 return fillWith(scale(1 - alpha) + noise.randomCPT().scale(alpha)).normalizeAsCPT();
835 }
836
837 template < GUM_Numeric GUM_SCALAR >
838 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::new_abs() const {
839 return Tensor< GUM_SCALAR >(*this).abs();
840 }
841
842 template < GUM_Numeric GUM_SCALAR >
843 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::new_sq() const {
844 return Tensor< GUM_SCALAR >(*this).sq();
845 }
846
847 template < GUM_Numeric GUM_SCALAR >
848 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::new_log2() const {
849 return Tensor< GUM_SCALAR >(*this).log2();
850 }
851
852 template < GUM_Numeric GUM_SCALAR >
853 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::new_sgn() const {
854 return Tensor< GUM_SCALAR >(*this).sgn();
855 }
856
857 template < GUM_Numeric GUM_SCALAR >
858 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator<<(const DiscreteVariable& v) {
859 this->add(v);
860 return *this;
861 }
862
864 template < GUM_Numeric GUM_SCALAR >
865 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator+(const Tensor< GUM_SCALAR >& p2) const {
866 if (p2.empty()) return Tensor< GUM_SCALAR >(*this).translate(p2.empty_value_);
867 if (this->empty()) return Tensor< GUM_SCALAR >(p2).translate(this->empty_value_);
868
869 return Tensor< GUM_SCALAR >(*this->content() + *p2.content());
870 }
871
873 template < GUM_Numeric GUM_SCALAR >
874 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator+(const GUM_SCALAR& v) const {
875 return Tensor< GUM_SCALAR >(*this).translate(v);
876 }
877
879 template < GUM_Numeric GUM_SCALAR >
881 if (this->nbrDim() != 1) return false;
882 if (this->sum() <= 0.0) return false;
883 return (this->min() >= 0.0) && (this->max() <= 1.0);
884 }
885
886 // max function between two evidence
887 template < GUM_Numeric GUM_SCALAR >
888 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator|(const Tensor< GUM_SCALAR >& p2) const {
889 if (!isEvidence() || !p2.isEvidence())
890 GUM_ERROR(InvalidArgument, "The tensors are not evidences.")
891 if (this->variable(0) != p2.variable(0))
892 GUM_ERROR(InvalidArgument, "The evidence are not on the same variable.")
893 Tensor< GUM_SCALAR > res(*this);
894 gum::Instantiation I(res);
895 for (I.setFirst(); !I.end(); ++I) {
896 res.set(I, std::max(res.get(I), p2.get(I)));
897 }
898 return res;
899 }
900
901 // min function between two evidence
902 template < GUM_Numeric GUM_SCALAR >
903 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator&(const Tensor< GUM_SCALAR >& p2) const {
904 if (!isEvidence() || !p2.isEvidence())
905 GUM_ERROR(InvalidArgument, "The tensors are not evidences.")
906 if (this->variable(0) != p2.variable(0))
907 GUM_ERROR(InvalidArgument, "The evidence are not on the same variable.")
908 Tensor< GUM_SCALAR > res(*this);
909 gum::Instantiation I(res);
910 for (I.setFirst(); !I.end(); ++I) {
911 res.set(I, std::min(res.get(I), p2.get(I)));
912 }
913 return res;
914 }
915
916 // complement function between two evidence
917 template < GUM_Numeric GUM_SCALAR >
918 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator~() const {
919 if (!isEvidence()) GUM_ERROR(InvalidArgument, "The tensor is not an evidence.")
920
921 Tensor< GUM_SCALAR > res(*this);
922 gum::Instantiation I(res);
923 for (I.setFirst(); !I.end(); ++I) {
924 res.set(I, 1 - res.get(I));
925 }
926 return res;
927 }
928
930 template < GUM_Numeric GUM_SCALAR >
931 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator-(const Tensor< GUM_SCALAR >& p2) const {
932 if (p2.empty()) return Tensor< GUM_SCALAR >(*this).translate(-p2.empty_value_);
933 if (this->empty()) {
934 auto p = Tensor< GUM_SCALAR >(p2);
935 p.apply([this](GUM_SCALAR x) { return this->empty_value_ - x; });
936 return p;
937 }
938 return Tensor< GUM_SCALAR >(*this->content() - *p2.content());
939 }
940
942 template < GUM_Numeric GUM_SCALAR >
943 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator-(const GUM_SCALAR& v) const {
944 return Tensor< GUM_SCALAR >(*this).translate(-v);
945 }
946
948 template < GUM_Numeric GUM_SCALAR >
949 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator*(const Tensor< GUM_SCALAR >& p2) const {
950 if (p2.empty()) return Tensor< GUM_SCALAR >(*this).scale(p2.empty_value_);
951 if (this->empty()) return Tensor< GUM_SCALAR >(p2).scale(this->empty_value_);
952
953 return Tensor< GUM_SCALAR >(*this->content() * *p2.content());
954 }
955
957 template < GUM_Numeric GUM_SCALAR >
958 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator*(const GUM_SCALAR& v) const {
959 return Tensor< GUM_SCALAR >(*this).scale(v);
960 }
961
963 template < GUM_Numeric GUM_SCALAR >
964 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator/(const Tensor< GUM_SCALAR >& p2) const {
965 if (p2.empty()) return Tensor< GUM_SCALAR >(*this).scale(1 / p2.empty_value_);
966 if (this->empty()) {
967 auto p = Tensor< GUM_SCALAR >(p2);
968 p.apply([this](GUM_SCALAR x) { return this->empty_value_ / x; });
969 return p;
970 }
971 return Tensor< GUM_SCALAR >(*this->content() / *p2.content());
972 }
973
975 template < GUM_Numeric GUM_SCALAR >
976 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::operator/(const GUM_SCALAR& v) const {
977 return Tensor< GUM_SCALAR >(*this).scale(1 / v);
978 }
979
980 template < GUM_Numeric GUM_SCALAR >
981 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator+=(const Tensor< GUM_SCALAR >& r) {
982 *this = *this + r;
983 return *this;
984 }
985
986 template < GUM_Numeric GUM_SCALAR >
987 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator+=(const GUM_SCALAR& v) {
988 this->translate(v);
989 return *this;
990 }
991
992 template < GUM_Numeric GUM_SCALAR >
993 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator*=(const Tensor< GUM_SCALAR >& r) {
994 *this = *this * r;
995 return *this;
996 }
997
998 template < GUM_Numeric GUM_SCALAR >
999 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator*=(const GUM_SCALAR& v) {
1000 this->scale(v);
1001 return *this;
1002 }
1003
1004 template < GUM_Numeric GUM_SCALAR >
1005 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator-=(const Tensor< GUM_SCALAR >& r) {
1006 *this = *this - r;
1007 return *this;
1008 }
1009
1010 template < GUM_Numeric GUM_SCALAR >
1011 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator-=(const GUM_SCALAR& v) {
1012 this->translate(-v);
1013 return *this;
1014 }
1015
1016 template < GUM_Numeric GUM_SCALAR >
1017 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator/=(const Tensor< GUM_SCALAR >& r) {
1018 *this = *this / r;
1019 return *this;
1020 }
1021
1022 template < GUM_Numeric GUM_SCALAR >
1023 Tensor< GUM_SCALAR >& Tensor< GUM_SCALAR >::operator/=(const GUM_SCALAR& v) {
1024 this->scale(1 / v);
1025 return *this;
1026 }
1027
1028 template < GUM_Numeric GUM_SCALAR >
1029 bool Tensor< GUM_SCALAR >::operator==(const Tensor< GUM_SCALAR >& r) const {
1030 if (this->empty()) {
1031 if (r.empty()) return this->empty_value_ == r.empty_value_;
1032 else return false;
1033 } else {
1034 if (r.empty()) return false;
1035 else return (*this->content_) == (*r.content_);
1036 }
1037 }
1038
1039 template < GUM_Numeric GUM_SCALAR >
1041 auto table = this->content();
1042 std::stringstream ss;
1043
1044 if (table->nbrDim() == 0) {
1045 Instantiation I(this);
1046 ss << "[" << this->get(I) << "]";
1047 return ss.str();
1048 }
1049 // size of the display from the configuration (tensor.columnWidthConsole, tensor.maxRowsConsole)
1050 const auto sizeFromConfiguration = [](const std::string& key, std::int64_t minimum) {
1051 const auto value = Configuration::instance().typed< std::int64_t >("tensor", key);
1052 if (value < minimum) {
1054 "The key tensor." << key << " of the configuration must be at least " << minimum
1055 << ".")
1056 }
1057 return static_cast< Size >(value);
1058 };
1059
1060 const Size colwidth = 6;
1061 const Size numberwidth = sizeFromConfiguration("columnWidthConsole", 6);
1062 const Size nbrLigMax = sizeFromConfiguration("maxRowsConsole", 1);
1063
1064 ss << std::left << std::fixed << std::endl;
1065 ss.precision(numberwidth - 5);
1066
1067 const auto& var = table->variable(0);
1068
1069 const Size nbparents = table->nbrDim() - 1;
1070 const Size nbcol = var.domainSize();
1071
1072 // box-drawing characters
1073 constexpr const char* vbar = "│"; // U+2502 single vertical
1074 constexpr const char* dvbar = "â•‘"; // U+2551 double vertical
1075 constexpr const char* hbar = "─"; // U+2500 single horizontal
1076
1077 const auto repeat_str = [](const char* s, Size n) {
1078 std::string r;
1079 const std::string unit(s);
1080 r.reserve(unit.size() * n);
1081 for (Size i = 0; i < n; i++)
1082 r += unit;
1083 return r;
1084 };
1085 const std::string maskparent = repeat_str(hbar, colwidth);
1086 const std::string masknumber = repeat_str(hbar, numberwidth);
1087
1088 if (nbparents > 0) ss << std::setw(nbparents * (colwidth + 1) - 1) << " " << dvbar;
1089 ss << " " << std::setw(nbcol * (numberwidth + 1) - 3)
1090 << var.name().substr(0, nbcol * (numberwidth + 1) - 3) << vbar;
1091 ss << std::endl;
1092
1093 if (nbparents > 0) {
1094 for (Idx i = 1; i <= nbparents; i++)
1095 ss << std::setw(colwidth) << table->variable(i).name().substr(0, colwidth)
1096 << (i < (Idx)nbparents ? vbar : dvbar);
1097 }
1098 for (Idx i = 0; i < nbcol; i++)
1099 ss << std::setw(numberwidth) << var.label(i).substr(0, numberwidth) << vbar;
1100 ss << std::endl;
1101
1102
1103 if (nbparents > 0) {
1104 for (Idx i = 1; i <= nbparents; i++)
1105 ss << maskparent << (i < (Idx)nbparents ? vbar : dvbar);
1106 }
1107 for (Idx i = 0; i < nbcol; i++)
1108 ss << masknumber << vbar;
1109 ss << std::endl;
1110 Instantiation I(*table);
1111
1112 const auto drawligne = [&]() {
1113 if (nbparents > 0) {
1114 for (Idx i = 1; i <= nbparents; i++)
1115 ss << std::setw(colwidth) << table->variable(i).label(I.val(i)).substr(0, colwidth)
1116 << (i < (Idx)nbparents ? vbar : dvbar);
1117 }
1118 for (I.setFirstVar(var); !I.end(); I.incVar(var))
1119 ss << " " << std::setw(numberwidth - 1) << table->get(I) << vbar;
1120 I.setFirstVar(var);
1121 ss << std::endl;
1122 };
1123
1124 if (const Size nbrLig = table->domainSize() / var.domainSize(); nbrLig < nbrLigMax * 2 + 1) {
1125 for (I.setFirst(); !I.end(); I.incNotVar(var))
1126 drawligne();
1127 } else {
1128 Size cpt = 0;
1129 for (I.setFirst(); !I.end(); I.incNotVar(var)) {
1130 cpt++;
1131 if (cpt > nbrLigMax) break;
1132 drawligne();
1133 }
1134 ss << "[..." << nbrLig - nbrLigMax * 2 << " more line(s) ...]" << std::endl;
1135 I.setLast();
1136 for (Idx revi = 1; revi < nbrLigMax; revi++)
1137 I.decNotVar(var);
1138 for (I.setFirstVar(var); !I.end(); I.incNotVar(var)) {
1139 drawligne();
1140 }
1141 }
1142
1143 return ss.str();
1144 }
1145
1146 template < GUM_Numeric GUM_SCALAR >
1147 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::evEq(const DiscreteVariable& v, double val) {
1148 const auto i = v.closestIndex(val);
1149
1151 p.add(v);
1152 p.fillWith(0);
1153 Instantiation I(p);
1154 I.chgVal(0, i);
1155 p.set(I, 1);
1156 return p;
1157 }
1158
1159 template < GUM_Numeric GUM_SCALAR >
1160 Tensor< GUM_SCALAR >
1161 Tensor< GUM_SCALAR >::evIn(const DiscreteVariable& v, double val1, double val2) {
1162 if (val2 < val1) {
1164 "val2 (" << val2 << ") must be greater than val1 (" << val1 << ").")
1165 }
1166 const auto i1 = v.closestIndex(val1);
1167 const auto i2 = v.closestIndex(val2);
1168
1170 p.add(v);
1171 p.fillWith(0);
1172 Instantiation I(p);
1173 for (Idx i = i1; i <= i2; i++) {
1174 I.chgVal(0, i);
1175 p.set(I, 1);
1176 }
1177 return p;
1178 }
1179
1180 template < GUM_Numeric GUM_SCALAR >
1181 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::evGt(const DiscreteVariable& v, double val) {
1182 const auto i = v.closestIndex(val);
1183 if (i == v.domainSize() - 1) { return evEq(v, val); }
1184
1186 p.add(v);
1187 p.fillWith(0);
1188 Instantiation I(p);
1189 for (Idx i2 = i + 1; i2 < v.domainSize(); i2++) {
1190 I.chgVal(0, i2);
1191 p.set(I, 1);
1192 }
1193 return p;
1194 }
1195
1196 template < GUM_Numeric GUM_SCALAR >
1197 Tensor< GUM_SCALAR > Tensor< GUM_SCALAR >::evLt(const DiscreteVariable& v, double val) {
1198 const auto i = v.closestIndex(val);
1199 if (i == 0) { return evEq(v, val); }
1200
1202 p.add(v);
1203 p.fillWith(0);
1204 Instantiation I(p);
1205 for (Idx i2 = 0; i2 < i; i2++) {
1206 I.chgVal(0, i2);
1207 p.set(I, 1);
1208 }
1209 return p;
1210 }
1211
1212 template < GUM_Numeric GUM_SCALAR >
1214 return this->content()->realSize() * sizeof(GUM_SCALAR);
1215 }
1216
1217 template < GUM_Numeric GUM_SCALAR >
1219 Idx value) {
1220 Tensor< GUM_SCALAR > pot;
1221
1222 pot.beginMultipleChanges();
1223 pot << var;
1224 pot.endMultipleChanges(GUM_SCALAR(0.0));
1225
1226 Instantiation I(pot);
1227 I.chgVal(var, value);
1228 pot.set(I, GUM_SCALAR(1.0));
1229
1230 return pot;
1231 }
1232
1233 template < GUM_Numeric GUM_SCALAR >
1235 std::string_view value) {
1236 return Tensor< GUM_SCALAR >::deterministicTensor(var, var.index(value));
1237 }
1238
1239 template < GUM_Numeric GUM_SCALAR >
1241 Tensor< GUM_SCALAR > pot;
1242
1243 pot.beginMultipleChanges();
1244 pot << var;
1245 pot.endMultipleChanges(GUM_SCALAR(1.0));
1246
1247 pot.normalize();
1248
1249 return pot;
1250 }
1251} /* namespace gum */
Exception base for argument error.
static Configuration & instance()
The global configuration.
T typed(std::string_view section, std::string_view key) const
Value of section.key converted according to its declared type.
Base class for discrete random variable.
virtual Idx closestIndex(double val) const =0
for numerical variables, returns the closest index for the value
virtual Idx index(std::string_view label) const =0
virtual Size domainSize() const =0
Exception : fatal (unknown ?) error.
The class for generic Hash Tables.
Definition hashTable.h:640
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
Class for assigning/browsing values to tuples of discrete variables.
Instantiation & chgVal(const DiscreteVariable &v, Idx newval)
Assign newval to variable v in the Instantiation.
bool end() const
Returns true if the Instantiation reached the end.
void inc()
Operator increment.
void incVar(const DiscreteVariable &v)
Operator increment for variable v only.
void setFirstNotVar(const DiscreteVariable &v)
Assign the first values to variables different of v.
void add(const DiscreteVariable &v) final
Adds a new variable in the Instantiation.
Instantiation()
Default constructor: creates an empty tuple.
void setFirstVar(const DiscreteVariable &v)
Assign the first value in the Instantiation for var v.
void incNotVar(const DiscreteVariable &v)
Operator increment for vars which are not 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.
void unsetEnd()
Alias for unsetOverflow().
void decNotVar(const DiscreteVariable &v)
Operator decrement for vars which are not v.
void setLast()
Assign the last values in the Instantiation.
Exception: at least one argument passed to a function is not what was expected.
Multidimensional matrix stored as an array in memory.
virtual void copyFrom(const MultiDimContainer< GUM_ELEMENT > &src) const
Basic copy of a MultiDimContainer.
virtual const MultiDimImplementation< GUM_ELEMENT > * content() const =0
Returns the implementation for this object (may be *this).
void populate(const std::vector< GUM_SCALAR > &v) const final
const MultiDimImplementation< GUM_SCALAR > * content() const final
void fill(const GUM_SCALAR &d) const final
const Sequence< const DiscreteVariable * > & variablesSequence() const final
MultiDimDecorator(MultiDimImplementation< GUM_SCALAR > *aContent=nullptr, GUM_SCALAR empty_value=(GUM_SCALAR) 0)
const DiscreteVariable & variable(Idx) const final
MultiDimDecorator< GUM_ELEMENT > & operator=(const MultiDimDecorator &from) noexcept
copy operator
bool contains(const DiscreteVariable &var) const final
GUM_SCALAR reduce(std::function< GUM_SCALAR(GUM_SCALAR, GUM_SCALAR) > f, GUM_SCALAR base) const final
void set(const Instantiation &i, const GUM_SCALAR &value) const final
MultiDimImplementation< GUM_SCALAR > * content_
void add(const DiscreteVariable &v) final
void apply(std::function< GUM_SCALAR(GUM_SCALAR) > f) const final
GUM_SCALAR get(const Instantiation &i) const final
virtual const Sequence< const DiscreteVariable * > & variablesSequence() const =0
Returns a const ref to the sequence of DiscreteVariable*.
virtual bool empty() const =0
Returns true if no var is in *this.
Exception : out of bound.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
bool exists(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:504
bool empty() const noexcept
Indicates whether the set is the empty set.
Definition set_tpl.h:613
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
Size size() const noexcept
Returns the number of elements in the set.
Definition set_tpl.h:607
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
GUM_SCALAR mean() const
compute the mean of a numerical discrete random variable @raise
Definition tensor_tpl.h:250
Tensor< GUM_SCALAR > & operator-=(const Tensor< GUM_SCALAR > &r)
the function to be used to add two Tensors
const Tensor< GUM_SCALAR > & translate(GUM_SCALAR v) const
add v to (each value of) *this
Definition tensor_tpl.h:486
Tensor< GUM_SCALAR > & operator/=(const Tensor< GUM_SCALAR > &r)
the function to be used to add two Tensors
Tensor< GUM_SCALAR > sumOut(const gum::VariableSet &del_vars) const
Projection using sum as operation (and implementation-optimized operations).
Definition tensor_tpl.h:498
GUM_SCALAR variance() const
compute the variance of a numerical discrete random variable @raise
Definition tensor_tpl.h:263
Tensor()
Default constructor.
Definition tensor_tpl.h:63
Idx draw() const
get a value at random from a 1-D distribution
Definition tensor_tpl.h:737
GUM_SCALAR entropy() const
entropy of the Tensor
Definition tensor_tpl.h:284
Tensor< GUM_SCALAR > operator|(const Tensor< GUM_SCALAR > &p2) const
the function to be used to add two Tensors
Definition tensor_tpl.h:888
const Tensor< GUM_SCALAR > & log2() const
apply $log_2(x)$ on every element of the container
Definition tensor_tpl.h:380
Tensor< GUM_SCALAR > extract(const Instantiation &inst) const
create a new Tensor extracted from *this given a partial instantiation
Definition tensor_tpl.h:729
const Tensor< GUM_SCALAR > & random() const
generate a random Tensor with each parameter in [0,1]
Definition tensor_tpl.h:786
Tensor< GUM_SCALAR > new_sq() const
Create a new tensor and apply $x^2$ on every element of the container.
Definition tensor_tpl.h:843
Tensor< GUM_SCALAR > isNonZeroMap() const
create a boolean-like tensor using the predicate isNonZero
Definition tensor_tpl.h:638
Tensor< GUM_SCALAR > minOut(const gum::VariableSet &del_vars) const
Projection using min as operation (and implementation-optimized operations).
Definition tensor_tpl.h:542
GUM_SCALAR stdDev() const
compute the stdDev of a numerical discrete random variable
Definition tensor_tpl.h:278
Tensor< GUM_SCALAR > putFirst(const DiscreteVariable *var) const
create a new Tensor with a certain variable in first
Definition tensor_tpl.h:699
Tensor< GUM_SCALAR > maxIn(const gum::VariableSet &kept_vars) const
Projection using max as operation (and implementation-optimized operations).
Definition tensor_tpl.h:625
static Tensor< GUM_SCALAR > evEq(const DiscreteVariable &v, double val)
numerical evidence generator
Tensor< GUM_SCALAR > sumIn(const gum::VariableSet &kept_vars) const
Projection using sum as operation (and implementation-optimized operations).
Definition tensor_tpl.h:586
Tensor< GUM_SCALAR > reorganize(const std::vector< const DiscreteVariable * > &vars) const
create a new Tensor with another order
Definition tensor_tpl.h:659
std::pair< Set< Instantiation >, GUM_SCALAR > argmax() const
Pair of the set of instantiation corresponding to the max and this max in the Tensor.
Definition tensor_tpl.h:773
Tensor< GUM_SCALAR > operator&(const Tensor< GUM_SCALAR > &p2) const
the function to be used to add two Tensors
Definition tensor_tpl.h:903
GUM_SCALAR max() const
max of all elements in the Tensor
Definition tensor_tpl.h:176
Tensor< GUM_SCALAR > * newFactory() const final
Definition tensor_tpl.h:151
const Tensor< GUM_SCALAR > & sgn() const
apply sgn(x)$ on every element of the container
Definition tensor_tpl.h:386
Size memoryFootprint() const
compute the (approximated) footprint in memory of the tensor
Tensor< GUM_SCALAR > new_sgn() const
Create a new tensor and apply sgn(x)$ on every element of the container.
Definition tensor_tpl.h:853
GUM_SCALAR maxNonOne() const
max of all non one elements in the Tensor
Definition tensor_tpl.h:195
Tensor< GUM_SCALAR > prodIn(const gum::VariableSet &kept_vars) const
Projection using multiplication as operation (and implementation-optimized operations).
Definition tensor_tpl.h:599
bool operator==(const Tensor< GUM_SCALAR > &r) const
the function to be used to add two Tensors
static Tensor< GUM_SCALAR > deterministicTensor(const DiscreteVariable &var, Idx value)
Tensor< GUM_SCALAR > new_log2() const
Create a new tensor and apply $log_2(x)$ on every element of the container.
Definition tensor_tpl.h:848
static Tensor< GUM_SCALAR > uniformTensor(const DiscreteVariable &var)
static Tensor< GUM_SCALAR > evGt(const DiscreteVariable &v, double val)
numerical evidence generator
GUM_SCALAR minNonZero() const
min of all non zero elements in the Tensor
Definition tensor_tpl.h:216
~Tensor() final
Destructor.
Definition tensor_tpl.h:145
GUM_SCALAR KL(const Tensor< GUM_SCALAR > &p) const
compute KL divergence between this and p Checks the compatibility and then compute KL divergence
Definition tensor_tpl.h:392
Set< Instantiation > findAll(GUM_SCALAR v) const
set of instantiation corresponding to the parameter v in the Tensor
Definition tensor_tpl.h:759
static Tensor< GUM_SCALAR > evIn(const DiscreteVariable &v, double val1, double val2)
numerical evidence generator
Tensor< GUM_SCALAR > prodOut(const gum::VariableSet &del_vars) const
Projection using multiplication as operation (and implementation-optimized operations).
Definition tensor_tpl.h:520
const Tensor< GUM_SCALAR > & fillWith(const Tensor< GUM_SCALAR > &src) const
copy a Tensor data using name of variables and labels (not necessarily the same variables in the same...
Definition tensor_tpl.h:305
Tensor< GUM_SCALAR > maxOut(const gum::VariableSet &del_vars) const
Projection using max as operation (and implementation-optimized operations).
Definition tensor_tpl.h:564
const Tensor< GUM_SCALAR > & noising(GUM_SCALAR alpha) const
add a noise in a CPT by mixing (1-alpha)this+alpha.randomCPT()
Definition tensor_tpl.h:829
bool isEvidence() const
is an evidence ? (marginal-like but has not to sum to 1)
Definition tensor_tpl.h:880
Tensor< GUM_SCALAR > & operator=(const Tensor< GUM_SCALAR > &src)
Default constructor.
Definition tensor_tpl.h:125
gum::VariableSet _complementVars_(const gum::VariableSet &del_vars) const
Definition tensor_tpl.h:648
Tensor< GUM_SCALAR > operator/(const Tensor< GUM_SCALAR > &p2) const
the function to be used to divide two Tensors
Definition tensor_tpl.h:964
const Tensor< GUM_SCALAR > & normalizeAsCPT(const Idx &varId=0) const
normalisation of this as a CPT for the variable varId
Definition tensor_tpl.h:448
const Tensor< GUM_SCALAR > & normalize() const
normalisation of this do nothing if sum is 0
Definition tensor_tpl.h:433
GUM_SCALAR expectedValue(std::function< GUM_SCALAR(const gum::Instantiation &) >) const
ExpectedValue computes the expectation of f over *this.
Definition tensor_tpl.h:234
Tensor< GUM_SCALAR > new_abs() const
Create a new tensor and apply abs on every element of the container.
Definition tensor_tpl.h:838
const Tensor< GUM_SCALAR > & inverse() const
the function to inverse (each value of) *this
Definition tensor_tpl.h:492
Tensor< GUM_SCALAR > & operator<<(const DiscreteVariable &v)
the function to be used to add two Tensors
Definition tensor_tpl.h:858
Tensor< GUM_SCALAR > minIn(const gum::VariableSet &kept_vars) const
Projection using min as operation (and implementation-optimized operations).
Definition tensor_tpl.h:612
Tensor< GUM_SCALAR > operator*(const Tensor< GUM_SCALAR > &p2) const
the function to be used to multiply two Tensors
Definition tensor_tpl.h:949
Tensor< GUM_SCALAR > operator-(const Tensor< GUM_SCALAR > &p2) const
the function to be used to subtract two Tensors
Definition tensor_tpl.h:931
const Tensor< GUM_SCALAR > & scale(GUM_SCALAR v) const
multiply (each value of) *this by v
Definition tensor_tpl.h:480
GUM_SCALAR min() const
min of all elements in the Tensor
Definition tensor_tpl.h:185
Tensor< GUM_SCALAR > & operator*=(const Tensor< GUM_SCALAR > &r)
the function to be used to add two Tensors
Definition tensor_tpl.h:993
GUM_SCALAR product() const
product of all elements in the Tensor
Definition tensor_tpl.h:167
std::pair< Set< Instantiation >, GUM_SCALAR > argmin() const
Pair of the set of instantiation corresponding to the min and this min in the Tensor.
Definition tensor_tpl.h:780
const Tensor< GUM_SCALAR > & sq() const
apply $x^2$ on every element of the container
Definition tensor_tpl.h:374
std::string toString() const final
the function to be used to add two Tensors
const Tensor< GUM_SCALAR > & randomCPT() const
generate a random CPT in the Tensor
Definition tensor_tpl.h:811
GUM_SCALAR sum() const
sum of all elements in the Tensor
Definition tensor_tpl.h:158
static Tensor< GUM_SCALAR > evLt(const DiscreteVariable &v, double val)
numerical evidence generator
const Tensor< GUM_SCALAR > & abs() const
Apply abs on every element of the container.
Definition tensor_tpl.h:422
Tensor< GUM_SCALAR > & operator+=(const Tensor< GUM_SCALAR > &r)
the function to be used to add two Tensors
Definition tensor_tpl.h:981
Tensor< GUM_SCALAR > operator+(const Tensor< GUM_SCALAR > &p2) const
the function to be used to add two Tensors
Definition tensor_tpl.h:865
Tensor< GUM_SCALAR > operator~() const
the function to be used to add two Tensors
Definition tensor_tpl.h:918
const Tensor< GUM_SCALAR > & randomDistribution() const
generate a random Distribution in the Tensor
Definition tensor_tpl.h:800
Complete concept for GUM_SCALAR template parameter.
Definition concepts.h:148
Typed, documented, sectioned configuration singleton read from an .ini content.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
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
GUM_SHARED_PUBLIC bool isNumerical(std::string_view val)
return true is a string contains a numerical (double) value
GUM_SHARED_PUBLIC double randomProba()
Returns a random double between 0 and 1 included (i.e.
std::vector< GUM_SCALAR > randomDistribution(Size n)
Return a random discrete distribution.
Useful macros for maths.
#define GUM_LOG2_OR_0(x)
Definition math_utils.h:72
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Set< const DiscreteVariable * > VariableSet
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.
GUM_ELEMENT projectProduct(const MultiDimImplementation< GUM_ELEMENT > &table, Instantiation *instantiation=0)
the function to be used to project a MultiDimImplementation using a Product
std::ostream & operator<<(std::ostream &stream, const AVLTree< Val, Cmp > &tree)
display the content of a tree
GUM_ELEMENT projectSum(const MultiDimImplementation< GUM_ELEMENT > &table, Instantiation *instantiation=0)
the function to be used to project a MultiDimImplementation using a sum
GUM_ELEMENT projectMin(const MultiDimImplementation< GUM_ELEMENT > &table, Instantiation *instantiation=0)
the function to be used to project a MultiDimImplementation using a Min
GUM_ELEMENT projectMax(const MultiDimImplementation< GUM_ELEMENT > &table, Instantiation *instantiation=0)
the function to be used to project a MultiDimImplementation using a Max
STL namespace.
Header of the Tensor class.