aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
IMarkovRandomField_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
50
51#include <algorithm>
52#include <limits>
53
58
59namespace gum {
60
61 // IMarkovRandomField
62
63 template < GUM_Numeric GUM_SCALAR >
67
68 template < GUM_Numeric GUM_SCALAR >
70 GUM_CONSTRUCTOR(IMarkovRandomField);
71 this->setProperty("name", name);
72 }
73
74 template < GUM_Numeric GUM_SCALAR >
79
80 template < GUM_Numeric GUM_SCALAR >
83 if (this != &source) { UGmodel::operator=(source); }
84
85 return *this;
86 }
87
88 template < GUM_Numeric GUM_SCALAR >
92
93 template < GUM_Numeric GUM_SCALAR >
95 Size res = 0;
96 for (auto f: factors()) {
97 res += f.second->domainSize();
98 }
99 return res;
100 }
101
102 template < GUM_Numeric GUM_SCALAR >
104 Size res = 0;
105 for (auto node: nodes()) {
106 auto v = variable(node).domainSize();
107 if (v > res) { res = v; }
108 }
109 return res;
110 }
111
112 template < GUM_Numeric GUM_SCALAR >
114 GUM_SCALAR res = 1.0;
115 for (auto elt: factors()) {
116 auto v = elt.second->min();
117 if (v < res) { res = v; }
118 }
119 return res;
120 }
121
122 template < GUM_Numeric GUM_SCALAR >
124 GUM_SCALAR res = 1.0;
125 for (auto elt: factors()) {
126 auto v = elt.second->max();
127 if (v > res) { res = v; }
128 }
129 return res;
130 }
131
132 template < GUM_Numeric GUM_SCALAR >
134 GUM_SCALAR res = 1.0;
135 for (auto elt: factors()) {
136 auto v = elt.second->minNonZero();
137 if (v < res) { res = v; }
138 }
139 return res;
140 }
141
142 template < GUM_Numeric GUM_SCALAR >
144 GUM_SCALAR res = 0.0;
145 for (auto elt: factors()) {
146 auto v = elt.second->maxNonOne();
147 if (v > res) { res = v; }
148 }
149 return res;
150 }
151
152 template < GUM_Numeric GUM_SCALAR >
154 Size param = 0;
155 double dSize = log10DomainSize();
156
157 for (auto factor: factors())
158 param += factor.second->content()->realSize();
159
160 std::stringstream s;
161 s << std::format("MRF{{nodes: {}, edges: {}, ", size(), graph().sizeEdges());
162
163 if (dSize > 6) s << std::format("domainSize: 10^{}", dSize);
164 else s << std::format("domainSize: {}", std::round(std::pow(10.0, dSize)));
165
166 s << std::format(", dim: {}}}", param);
167
168 return s.str();
169 }
170
171 template < GUM_Numeric GUM_SCALAR >
173 return toDot(dot::DotOptions());
174 }
175
176 template < GUM_Numeric GUM_SCALAR >
178 const auto style = dot::DotStyle::read();
179 dot::DotWriter writer(false, this->propertyWithDefault("name", ""));
180 dot::writePreamble(writer, style, options);
181
182 for (const auto node: nodes()) {
183 const auto& name = variable(node).name();
184 writer.node(name,
186 options.node(node),
187 "",
188 "(" + std::to_string(node) + ") " + name));
189 }
190
191 for (const auto& edge: edges()) {
192 auto attributes = dot::arcAttributes(options.edge(edge.first(), edge.second()));
193 dot::addDefaultAttribute(attributes,
194 "tooltip",
195 std::to_string(edge.first()) + "&nbsp;&mdash;&nbsp;"
196 + std::to_string(edge.second()));
197 dot::addDefaultAttribute(attributes, "fontsize", "10");
198 writer.edge(variable(edge.first()).name(), variable(edge.second()).name(), attributes);
199 }
200
201 return writer.str();
202 }
203
204 template < GUM_Numeric GUM_SCALAR >
208
209 template < GUM_Numeric GUM_SCALAR >
210 std::string
212 const auto style = dot::FactorGraphDotStyle::read();
213 dot::DotWriter writer(false, this->propertyWithDefault("name", ""));
214 dot::writePreamble(writer, style, options);
215 writer.edgeDefaults({{"len", dot::DotWriter::number(style.edgeLength)}});
216
217 // the variables
218 for (const auto node: nodes()) {
219 const auto& name = variable(node).name();
220 auto attributes = dot::nodeAttributes(style,
221 options.node(node),
222 "",
223 "(" + std::to_string(node) + ") " + name);
224 dot::addDefaultAttribute(attributes, "height", "0");
225 dot::addDefaultAttribute(attributes, "width", "0");
226 dot::addDefaultAttribute(attributes, "margin", "0.04");
227 dot::addDefaultAttribute(attributes, "shape", "rectangle");
228 writer.node(name, attributes);
229 }
230
231 // the factors, in the order of the identifiers of their variables
232 std::vector< std::vector< NodeId > > scopes;
233 for (const auto& kv: factors()) {
234 std::vector< NodeId > scope(kv.first.begin(), kv.first.end());
235 std::sort(scope.begin(), scope.end());
236 scopes.push_back(std::move(scope));
237 }
238 std::sort(scopes.begin(), scopes.end());
239
240 auto factorName = [this](const std::vector< NodeId >& scope) {
241 std::string name = "f";
242 for (const auto node: scope)
243 name += "#" + variable(node).name();
244 return name;
245 };
246
247 // a factor is a point, whose font color is adaptive against its own background
248 auto factorStyle = static_cast< dot::DotStyle >(style);
249 factorStyle.nodeBgColor = style.factorBgColor;
250 for (const auto& scope: scopes) {
251 auto attributes = dot::nodeAttributes(factorStyle, options.factor(scope));
252 dot::addDefaultAttribute(attributes, "height", "0.1");
253 dot::addDefaultAttribute(attributes, "width", "0.1");
254 dot::addDefaultAttribute(attributes, "shape", "point");
255 dot::addDefaultAttribute(attributes, "fontcolor", style.factorFgColor);
256 dot::addDefaultAttribute(attributes, "fillcolor", style.factorBgColor);
257 writer.node(factorName(scope), attributes);
258 }
259
260 // the links variable -- factor
261 for (const auto& scope: scopes)
262 for (const auto node: scope)
263 writer.edge(factorName(scope), variable(node).name());
264
265 return writer.str();
266 }
267
268 template < GUM_Numeric GUM_SCALAR >
270 if (size() != from.size()) { return false; }
271
272 if (sizeEdges() != from.sizeEdges()) { return false; }
273
274 // alignment of variables between the 2 BNs
276
277 for (auto node: nodes()) {
278 const auto& v1 = variable(node);
279 if (!from.exists(v1.name())) return false;
280 const auto& v2 = from.variableFromName(v1.name());
281 if (v1 != v2) return false;
282
283 alignment.insert(&variable(node), &from.variableFromName(v1.name()));
284 }
285
286 for (const auto& elt: factors()) {
287 const auto& key = elt.first;
288 const auto& factor = *elt.second;
289
290 NodeSet fromkey;
291 for (const auto n: key)
292 fromkey.insert(from.idFromName(variable(n).name()));
293
294 if (!from.factors().exists(fromkey)) { return false; }
295
296 const auto& fromfactor = from.factor(fromkey);
297
299 Instantiation j(fromfactor);
300 // the tolerance applies to the squared difference: two values are equal when
301 // |a - b| <= sqrt(epsilonStandard), i.e. 1e-3 by default
302 const GUM_SCALAR tolerance = static_cast< GUM_SCALAR >(config().epsilonStandard());
303 for (i.setFirst(); !i.end(); i.inc()) {
304 for (Idx indice = 0; indice < factor.nbrDim(); ++indice) {
305 const DiscreteVariable* p = &(i.variable(indice));
306 j.chgVal(*(alignment.second(p)), i.val(*p));
307 }
308
309 if (std::pow(factor.get(i) - fromfactor.get(j), (GUM_SCALAR)2) > tolerance) {
310 return false;
311 }
312 }
313 }
314 return true;
315 }
316
317 template < GUM_Numeric GUM_SCALAR >
318 std::ostream& operator<<(std::ostream& output, const IMarkovRandomField< GUM_SCALAR >& bn) {
319 output << bn.toString();
320 return output;
321 }
322
323 template < GUM_Numeric GUM_SCALAR >
324 const NodeSet&
326 if (!this->exists(name)) {
327 GUM_ERROR(NotFound, "No factor containing the variable <" << name << ">")
328 }
330 }
331
332 // visit the nodes and add some of node from soids in minimal
333 template < GUM_Numeric GUM_SCALAR >
335 const NodeSet& soids,
336 NodeSet& minimal,
337 NodeSet& alreadyVisited) const {
338 if (alreadyVisited.contains(node)) return;
339 alreadyVisited << node;
340
341 if (soids.contains(node)) {
342 minimal << node;
343 } else {
344 for (auto neig: graph_.neighbours(node))
345 _minimalCondSetVisit_(neig, soids, minimal, alreadyVisited);
346 }
347 }
348
349 template < GUM_Numeric GUM_SCALAR >
351 const NodeSet& soids) const {
352 if (soids.contains(target)) return NodeSet({target});
353
354 NodeSet res;
355 NodeSet alreadyVisited;
356 alreadyVisited << target;
357
358 for (auto neig: graph_.neighbours(target))
359 _minimalCondSetVisit_(neig, soids, res, alreadyVisited);
360 return res;
361 }
362
363 template < GUM_Numeric GUM_SCALAR >
365 const NodeSet& soids) const {
366 NodeSet res;
367 for (auto node: targets) {
368 res += minimalCondSet(node, soids);
369 }
370 return res;
371 }
372} /* namespace gum */
Class representing Markov random fields.
const T2 & second(const T1 &first) const
Returns the second value of a pair given its first value.
void insert(const T1 &first, const T2 &second)
Inserts a new association in the gum::Bijection.
Set of pairs of elements with fast search for both elements.
Definition bijection.h:1640
double epsilonStandard() const noexcept
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
const DiscreteVariable & variable(NodeId id) const override
Returns a constant reference over a variable given its node id.
Base class for discrete random variable.
void setProperty(std::string_view name, std::string_view value)
Add or change a property of this GraphicalModel.
double log10DomainSize() const
const std::string & propertyWithDefault(std::string_view name, const std::string &byDefault) const
Return the value of the property name of this GraphicalModel.
Class representing the minimal interface for Markov random field.
virtual std::string toDot() const
IMarkovRandomField()
Default constructor.
virtual const Tensor< GUM_SCALAR > & factor(const NodeSet &varIds) const =0
Returns the factor of a set of variable.
~IMarkovRandomField() override
Destructor.
virtual const FactorTable< GUM_SCALAR > & factors() const =0
Returns the set of factors as a IMarkovRandomField::FactorTable.
virtual std::string toDotAsFactorGraph() const
void _minimalCondSetVisit_(NodeId node, const NodeSet &soids, NodeSet &minimal, NodeSet &alreadyVisited) const
Size dim() const
Returns the dimension (the number of free parameters) in this bayes net.
bool operator==(const IMarkovRandomField< GUM_SCALAR > &from) const
This operator compares 2 BNs !
NodeSet minimalCondSet(NodeId target, const NodeSet &soids) const
IMarkovRandomField< GUM_SCALAR > & operator=(const IMarkovRandomField< GUM_SCALAR > &source)
Copy operator.
virtual const NodeSet & smallestFactorFromNode(NodeId node) const =0
Returns the smallest factor that contains this variable.
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.
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.
Exception : the element we looked for cannot be found.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
UGmodel()
Default constructor.
Definition UGmodel.cpp:49
const NodeGraphPart & nodes() const final
Returns a named copy of the internal undirected graph: each node id is assigned the name of the corre...
Definition UGmodel_inl.h:97
UGmodel & operator=(const UGmodel &source)
Private copy operator.
Definition UGmodel.cpp:62
bool exists(NodeId node) const final
Return true if this node exists in this graphical model.
Definition UGmodel_inl.h:89
UndiGraph graph_
The DAG of this Directed Graphical Model.
Definition UGmodel.h:195
const EdgeSet & edges() const
return true if the edge node1-node2 exists in the UGModel
Definition UGmodel_inl.h:73
UndiGraph graph() const
Returns a named copy of the internal undirected graph: each node id is assigned the name of the corre...
Definition UGmodel_inl.h:61
Size sizeEdges() const
Returns the number of arcs in this Directed Graphical Model.
Definition UGmodel_inl.h:71
Size size() const final
Returns the number of variables in this Directed Graphical Model.
Definition UGmodel_inl.h:68
The options given to a toDot(const DotOptions&).
Definition dotOptions.h:110
const DotArcOptions * edge(Size a, Size b) const
the options of the undirected edge between a and b, given for (a, b) or for (b, a),...
const DotNodeOptions * factor(const std::vector< Size > &variables) const
the options of the factor on these variables (in any order), or nullptr if none was given
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.
Definition dotWriter.h:100
void edgeDefaults(const DotAttributes &attributes)
edge [attributes];, the default attributes of the edges that follow (none : does nothing).
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).
static std::string number(double value)
The shortest text that reads back as value (0.5, 1, 1e-05).
Definition dotWriter.cpp:93
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.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#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
Size NodeId
Type for node ids.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
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
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
std::ostream & operator<<(std::ostream &stream, const AVLTree< Val, Cmp > &tree)
display the content of a tree
The look shared by all the graphs: size, direction, layout, colors of the arcs and of the nodes.
Definition dotStyle.h:76
static DotStyle read()
the style of the graphs of the section notebook
Definition dotStyle.cpp:89
std::string nodeBgColor
background color of the nodes
Definition dotStyle.h:86
static FactorGraphDotStyle read()
Definition dotStyle.cpp:120
Header of the Tensor class.