aGrUM 3.0.0
a C++ library for (probabilistic) graphical models
ConstraintBasedLearning.cpp
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
47
51
52namespace gum {
53
54 namespace learning {
55
56 // ##########################################################################
57 // Constructors / Destructors
58 // ##########################################################################
59
63
67
75
84
86
89 ApproximationScheme::operator=(from);
95 _maxLog_ = from._maxLog_;
96 return *this;
97 }
98
100 ApproximationScheme::operator=(std::move(from));
101 _forbiddenGraph_ = std::move(from._forbiddenGraph_);
102 _mandatoryGraph_ = std::move(from._mandatoryGraph_);
103 _maxIndegree_ = from._maxIndegree_;
104 _initialMarks_ = std::move(from._initialMarks_);
105 _latentCouples_ = std::move(from._latentCouples_);
106 _maxLog_ = from._maxLog_;
107 return *this;
108 }
109
110 // ##########################################################################
111 // Constraint setters
112 // ##########################################################################
113
115 _mandatoryGraph_ = mandaGraph;
116 }
117
119 _forbiddenGraph_ = forbidGraph;
120 }
121
123
125 const HashTable< std::pair< NodeId, NodeId >, char >& constraints) {
126 _initialMarks_ = constraints;
127 }
128
129 const std::vector< Arc > ConstraintBasedLearning::latentVariables() const {
130 return _latentCouples_;
131 }
132
133 // ##########################################################################
134 // Template methods
135 // ##########################################################################
136
140
144
145 // ##########################################################################
146 // Constraint checks
147 // ##########################################################################
148
150 return _forbiddenGraph_.existsArc(x, y);
151 }
152
154 return _forbiddenGraph_.existsArc(x, y) && _forbiddenGraph_.existsArc(y, x);
155 }
156
158 return graph.parents(x).size() >= _maxIndegree_;
159 }
160
164
165 // ##########################################################################
166 // Graph utilities
167 // ##########################################################################
168
170 const NodeId n1,
171 const NodeId n2) {
172 for (const auto parent: graph.parents(n2)) {
173 if (graph.existsArc(n2, parent)) continue; // double arc — skip
174 if (parent == n1) continue; // trivial path — not counted
175 if (_existsDirectedPath_(graph, n1, parent)) return true;
176 }
177 return false;
178 }
179
181 const NodeId n1,
182 const NodeId n2) {
183 List< NodeId > nodeFIFO;
184 Set< NodeId > mark;
185
186 mark.insert(n2);
187 nodeFIFO.pushBack(n2);
188
189 NodeId current;
190 while (!nodeFIFO.empty()) {
191 current = nodeFIFO.front();
192 nodeFIFO.popFront();
193 for (const auto new_one: graph.parents(current)) {
194 if (graph.existsArc(current, new_one)) continue; // double arc — skip
195 if (new_one == n1) return true;
196 if (mark.exists(new_one)) continue;
197 mark.insert(new_one);
198 nodeFIFO.pushBack(new_one);
199 }
200 }
201 return false;
202 }
203
205 gum::ArcSet L;
206 for (gum::NodeId x: mg.nodes())
207 for (NodeId y: mg.parents(x))
208 if (mg.parents(y).contains(x)) {
209 if (x > y) continue;
210 else L.insert(gum::Arc(x, y));
211 }
212
213 if (not L.empty()) {
214 while (true) {
215 bool withdrawFlag_L = false;
216 for (auto arc: ArcSet(L)) {
217 bool tail_head = _existsDirectedPath_(mg, arc.tail(), arc.head());
218 bool head_tail = _existsDirectedPath_(mg, arc.head(), arc.tail());
219 bool withdrawFlag_arc = false;
220
221 if (tail_head && !head_tail) {
222 mg.eraseArc(Arc(arc.head(), arc.tail()));
223 withdrawFlag_arc = true;
224 } else if (!tail_head && head_tail) {
225 mg.eraseArc(Arc(arc.tail(), arc.head()));
226 withdrawFlag_arc = true;
227 } else if (!tail_head && !head_tail) {
228 mg.eraseArc(Arc(arc.head(), arc.tail()));
229 withdrawFlag_arc = true;
230 }
231
232 if (withdrawFlag_arc) {
233 L.erase(arc);
234 withdrawFlag_L = true;
235 }
236 }
237 if (L.empty()) break;
238
239 // no arc was processed this pass — break cycle by erasing one arc arbitrarily
240 if (!withdrawFlag_L) {
241 auto arc = *L.begin();
242 mg.eraseArc(Arc(arc.head(), arc.tail()));
243 mg.eraseArc(Arc(arc.tail(), arc.head()));
244 L.erase(arc);
245 }
246 }
247 }
248 }
249
251 for (const auto& arc: _mandatoryGraph_.arcs()) {
252 if (graph.existsEdge(arc.head(), arc.tail())) graph.eraseEdge(Edge(arc.head(), arc.tail()));
253 if (!graph.existsArc(arc.tail(), arc.head())) {
254 GUM_SL_EMIT(arc.tail(),
255 arc.head(),
256 "Add Arc" << arc.tail() << "->" << arc.head(),
257 "Mandatory")
258 graph.addArc(arc.tail(), arc.head());
259 }
260 }
261 for (const Arc& arc: _forbiddenGraph_.arcs()) {
262 if (graph.existsEdge(Edge(arc.tail(), arc.head()))) {
263 graph.eraseEdge(Edge(arc.tail(), arc.head()));
264 graph.addArc(arc.head(), arc.tail());
265 GUM_SL_EMIT(arc.head(),
266 arc.tail(),
267 "Add Arc" << arc.head() << "->" << arc.tail(),
268 "Forbidden in the other orientation")
269 }
270 }
271 }
272
275 for (NodeId n: template_graph.nodes())
276 graph.addNodeWithId(n);
277
278 auto addEdgeIfAllowed = [&](NodeId x, NodeId y) {
279 if (x > y) std::swap(x, y);
280 if (isForbiddenEdge_(x, y))
281 GUM_SL_EMIT(x, y, "Remove " << x << " - " << y, "Constraints : Forbidden edge")
282 else graph.addEdge(x, y);
283 };
284
285 if (template_graph.edges().empty()) {
286 // node-only template: constraint-based learning always starts from complete graph
287 const std::vector< NodeId > nodes(template_graph.nodes().begin(),
288 template_graph.nodes().end());
289 for (std::size_t i = 0; i < nodes.size(); ++i)
290 for (std::size_t j = i + 1; j < nodes.size(); ++j)
291 addEdgeIfAllowed(nodes[i], nodes[j]);
292 } else {
293 for (const auto& edge: template_graph.edges())
294 addEdgeIfAllowed(edge.first(), edge.second());
295 }
296
297 return graph;
298 }
299
300 std::vector< ThreePoints >
302 std::vector< ThreePoints > triples;
303 for (NodeId z: graph) {
304 for (NodeId x: graph.neighbours(z)) {
305 for (NodeId y: graph.neighbours(z)) {
306 if (y < x && !graph.existsEdge(x, y) && !graph.existsArc(x, y)
307 && !graph.existsArc(y, x)) {
308 triples.emplace_back(x, y, z);
309 }
310 }
311 }
312 }
313 return triples;
314 }
315
316 } /* namespace learning */
317
318} /* namespace gum */
Abstract base class for constraint-based structure learning algorithms.
#define GUM_SL_EMIT(x, y, action, explain)
ApproximationScheme(bool verbosity=false)
const NodeSet & parents(NodeId id) const
returns the set of nodes with arc ingoing to a given node
virtual void eraseArc(const Arc &arc)
removes an arc from the ArcGraphPart
The base class for all directed edges.
Base class for dag.
Definition DAG.h:121
Base class for all oriented graphs.
Definition diGraph.h:132
const EdgeSet & edges() const
returns the set of edges stored within the EdgeGraphPart
The base class for all undirected edges.
The class for generic Hash Tables.
Definition hashTable.h:640
Generic doubly linked lists.
Definition list.h:378
Val & front() const
Returns a reference to first element of a list, if any.
Definition list_tpl.h:1694
Val & pushBack(const Val &val)
Inserts a new element (a copy) at the end of the chained list.
Definition list_tpl.h:1481
bool empty() const noexcept
Returns a boolean indicating whether the chained list is empty.
Definition list_tpl.h:1822
void popFront()
Removes the first element of a List, if any.
Definition list_tpl.h:1816
Base class for mixed graphs.
Definition mixedGraph.h:146
const NodeGraphPart & nodes() const
return *this as a NodeGraphPart
node_iterator begin() const noexcept
a begin iterator to parse the set of nodes contained in the NodeGraphPart
const node_iterator & end() const noexcept
the end iterator to parse the set of nodes contained in the NodeGraphPart
Base class for partially directed acyclic graphs.
Definition PDAG.h:130
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
iterator begin() const
The usual unsafe begin iterator to parse the set.
Definition set_tpl.h:409
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
void erase(const Key &k)
Erases an element from the set.
Definition set_tpl.h:553
Abstract base class for constraint-based structure learning algorithms.
void setMandatoryGraph(const gum::DAG &mandaGraph)
std::vector< ThreePoints > unshieldedTriples_(const MixedGraph &graph)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
static bool _existsNonTrivialDirectedPath_(const MixedGraph &graph, NodeId n1, NodeId n2)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
gum::MeekRules meekRules_
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
bool isForbiddenEdge_(NodeId x, NodeId y) const
bool isMaxIndegree_(const MixedGraph &graph, NodeId x)
void setForbiddenGraph(const gum::DiGraph &forbidGraph)
const std::vector< Arc > latentVariables() const
bool isArcValid_(const MixedGraph &graph, NodeId x, NodeId y)
void orientDoubleHeadedArcs_(MixedGraph &mg)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
PDAG learnPDAG(MixedGraph graph)
learns the essential graph (CPDAG)
HashTable< std::pair< NodeId, NodeId >, char > _initialMarks_
static bool _existsDirectedPath_(const MixedGraph &graph, NodeId n1, NodeId n2)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
void addConstraints(const HashTable< std::pair< NodeId, NodeId >, char > &constraints)
virtual MixedGraph learnMixedStructure(MixedGraph graph)=0
ConstraintBasedLearning & operator=(const ConstraintBasedLearning &)
DAG learnDAG(MixedGraph graph)
learns a DAG
void applyStructuralConstraints_(MixedGraph &graph)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
MixedGraph initGraph_(const MixedGraph &template_graph)
Builds a complete MixedGraph on the nodes of template_graph, minus edges forbidden by structural cons...
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size NodeId
Type for node ids.
Set< Arc > ArcSet
Some typdefs and define for shortcuts ...
Class hash tables iterators.
Base classes for mixed directed/undirected graphs.
include the inlined functions if necessary
Definition CSVParser.h:55
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
STL namespace.