aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
causalFormula_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
45#pragma once
46
47
48#include <algorithm>
49#include <vector>
50
52
53namespace gum {
54 // ---------- helpers ----------
55
56 template < GUM_Numeric GUM_SCALAR >
58 const Set< std::string >& names) {
59 NodeSet ids;
60 for (const auto& n: names) {
61 ids.insert(cm.idFromName(n)); // throws NotFound if unknown
62 }
63 return ids;
64 }
65
66 template < GUM_Numeric GUM_SCALAR >
68 const NodeSet lat = _cm.latentVariablesIds();
69 const DAG dag = _cm.causalDAG();
70 auto checkObserved = [&](const NodeSet& S) {
71 for (const auto& id: S) {
72 if (!dag.existsNode(id) || lat.contains(id)) {
74 "CausalFormula: variable id " + std::to_string(id)
75 + " is not an observed variable of the model.");
76 }
77 }
78 };
79 checkObserved(_on);
80 checkObserved(_doing);
81 checkObserved(_knowing);
82 }
83
84 template < GUM_Numeric GUM_SCALAR >
86 // Ensure pairwise disjointness: on ∩ doing = ∅, on ∩ knowing = ∅, doing ∩ knowing = ∅
87 for (const auto& id: _on) {
88 if (_doing.contains(id))
89 GUM_ERROR(OperationNotAllowed, "Variable cannot be both in 'on' and 'doing'");
90 if (_knowing.contains(id))
91 GUM_ERROR(OperationNotAllowed, "Variable cannot be both in 'on' and 'knowing'");
92 }
93 for (const auto& id: _doing) {
94 if (_knowing.contains(id))
95 GUM_ERROR(OperationNotAllowed, "Variable cannot be both in 'doing' and 'knowing'");
96 }
97 }
98
99 // ---------- constructors ----------
100
101 template < GUM_Numeric GUM_SCALAR >
114
115 template < GUM_Numeric GUM_SCALAR >
117 std::unique_ptr< ASTtree< GUM_SCALAR > > root,
118 const NodeSet& on,
119 const NodeSet& doing,
120 const NodeSet& knowing,
121 std::string_view explanation) :
122 _cm(cm), _root(std::move(root)), _on(on), _doing(doing), _knowing(knowing),
126 }
127
128 template < GUM_Numeric GUM_SCALAR >
130 _cm(other._cm), _root(other._root ? other._root->copy() : nullptr), _on(other._on),
131 _doing(other._doing), _knowing(other._knowing), _explanation(other._explanation) {}
132
133 // ---------- core API ----------
134
135 // causalFormula_tpl.h (or inline in the header)
136 template < GUM_Numeric GUM_SCALAR >
138 return static_cast< bool >(_root);
139 }
140
141 template < GUM_Numeric GUM_SCALAR >
142 const ASTtree< GUM_SCALAR >& CausalFormula< GUM_SCALAR >::root() const {
143 if (!_root) GUM_ERROR(OperationNotAllowed, "No AST: effect not identified.");
144 return *_root;
145 }
146
147 template < GUM_Numeric GUM_SCALAR >
148 Tensor< GUM_SCALAR > CausalFormula< GUM_SCALAR >::eval() const {
149 if (!_root) {
150 GUM_ERROR(gum::OperationNotAllowed,
151 "CausalFormula::eval() called on a non-identified formula.");
152 }
153 return _root->eval(_cm.observationalBN());
154 }
155
156 template < GUM_Numeric GUM_SCALAR >
158 if (!_root) return "[unidentifiable]";
159 return _root->toString();
160 }
161
162 template < GUM_Numeric GUM_SCALAR >
163 std::string CausalFormula< GUM_SCALAR >::toLatex(std::string_view doOperatorPrefix,
164 std::string_view doOperatorSuffix) const {
165 if (!_root) return "[unidentifiable]";
166
167 // Track variable name occurrences for prime management in AST LaTeX
169
170 auto addNames = [&](const NodeSet& S) {
171 for (const auto& id: S) {
172 const auto name = _cm.nameFromId(id);
173 if (!nameOccur.exists(name)) nameOccur.insert(name, 1);
174 }
175 };
176 addNames(_on);
177 addNames(_doing);
178 addNames(_knowing);
179
180 return latexQuery(doOperatorPrefix, doOperatorSuffix) + " = " + _root->toLatex(nameOccur);
181 }
182
183 template < GUM_Numeric GUM_SCALAR >
184 std::string CausalFormula< GUM_SCALAR >::latexQuery(std::string_view doOperatorPrefix,
185 std::string_view doOperatorSuffix) const {
186 auto namesSorted = [&](const NodeSet& S) {
187 std::vector< std::string > res;
188 res.reserve(S.size());
189 for (const auto& id: S)
190 res.emplace_back(_cm.nameFromId(id));
191 std::sort(res.begin(), res.end());
192 return res;
193 };
194
195 const auto onNames = namesSorted(_on);
196 const auto doingNames = namesSorted(_doing);
197 const auto knowingNames = namesSorted(_knowing);
198
199 std::stringstream ss;
200 ss << "P\\left(";
201
202 for (size_t i = 0; i < onNames.size(); ++i) {
203 ss << onNames[i];
204 if (i + 1 < onNames.size()) ss << ",";
205 }
206
207 if (!doingNames.empty() || !knowingNames.empty()) {
208 ss << " \\mid ";
209
210 if (!doingNames.empty()) {
211 ss << doOperatorPrefix << doingNames.front();
212 for (size_t i = 1; i < doingNames.size(); ++i)
213 ss << "," << doingNames[i];
214 ss << doOperatorSuffix;
215 }
216
217 if (!knowingNames.empty()) {
218 if (!doingNames.empty()) ss << ",";
219 ss << knowingNames.front();
220 for (size_t i = 1; i < knowingNames.size(); ++i)
221 ss << "," << knowingNames[i];
222 }
223 }
224
225 ss << "\\right)";
226 return ss.str();
227 }
228
229 template < GUM_Numeric GUM_SCALAR >
230 std::unique_ptr< CausalFormula< GUM_SCALAR > > CausalFormula< GUM_SCALAR >::copy() const {
231 return std::make_unique< CausalFormula< GUM_SCALAR > >(_cm,
232 _root->copy(),
233 _on,
234 _doing,
235 _knowing);
236 }
237
238 // ---------- convenience name accessors ----------
239
240 template < GUM_Numeric GUM_SCALAR >
241 std::vector< std::string > CausalFormula< GUM_SCALAR >::onNames() const {
242 std::vector< std::string > out;
243 out.reserve(_on.size());
244 for (const auto& id: _on)
245 out.emplace_back(_cm.nameFromId(id));
246 std::sort(out.begin(), out.end());
247 return out;
248 }
249
250 template < GUM_Numeric GUM_SCALAR >
251 std::vector< std::string > CausalFormula< GUM_SCALAR >::doingNames() const {
252 std::vector< std::string > out;
253 out.reserve(_doing.size());
254 for (const auto& id: _doing)
255 out.emplace_back(_cm.nameFromId(id));
256 std::sort(out.begin(), out.end());
257 return out;
258 }
259
260 template < GUM_Numeric GUM_SCALAR >
261 std::vector< std::string > CausalFormula< GUM_SCALAR >::knowingNames() const {
262 std::vector< std::string > out;
263 out.reserve(_knowing.size());
264 for (const auto& id: _knowing)
265 out.emplace_back(_cm.nameFromId(id));
266 std::sort(out.begin(), out.end());
267 return out;
268 }
269
270 // ---------- accessors ----------
271
272 template < GUM_Numeric GUM_SCALAR >
276
277 template < GUM_Numeric GUM_SCALAR >
279 return _on;
280 }
281
282 template < GUM_Numeric GUM_SCALAR >
284 return _doing;
285 }
286
287 template < GUM_Numeric GUM_SCALAR >
289 return _knowing;
290 }
291
292 template < GUM_Numeric GUM_SCALAR >
293 const std::string& CausalFormula< GUM_SCALAR >::explanation() const {
294 return _explanation;
295 }
296
297} // namespace gum
Represents an identified causal formula and its query context.
Tensor< GUM_SCALAR > eval() const
Evaluates the formula's AST to compute the resulting probability distribution.
const NodeSet & on() const
std::vector< std::string > doingNames() const
const std::string _explanation
const NodeSet _knowing
static NodeSet _toNodeSetFromNames_(const CausalModel< GUM_SCALAR > &cm, const Set< std::string > &names)
Convert a set of names to a set of node ids (validates existence).
const NodeSet _on
std::vector< std::string > knowingNames() const
std::string toLatex(std::string_view doOperatorPrefix="do(", std::string_view doOperatorSuffix=")") const
Generates a full LaTeX equation: Query = Formula.
const CausalModel< GUM_SCALAR > & _cm
const NodeSet & knowing() const
std::vector< std::string > onNames() const
Convenience: return names corresponding to stored node ids (sorted).
const std::string & explanation() const
const CausalModel< GUM_SCALAR > & cm() const
CausalFormula(const CausalModel< GUM_SCALAR > &cm, std::unique_ptr< ASTtree< GUM_SCALAR > > root, const Set< std::string > &on, const Set< std::string > &doing, const Set< std::string > &knowing=Set< std::string >{}, std::string_view explanation="")
Constructs a CausalFormula object (variables given by names).
void _ensureNoVariablesOverlap() const
Verifies that all variables (_on, _knowing, _doing) have no intersection.
const NodeSet & doing() const
bool isIdentified() const noexcept
Whether the causal effect has been identified.
std::unique_ptr< ASTtree< GUM_SCALAR > > _root
std::string toString() const
Generates a string representation of the formula's AST.
void _ensureVariablesExist() const
Verifies that all variables (_on, _knowing, _doing) exist in the BN.
const ASTtree< GUM_SCALAR > & root() const
Access the root AST node of the identified formula.
const NodeSet _doing
std::unique_ptr< CausalFormula< GUM_SCALAR > > copy() const
Creates a deep copy of the CausalFormula (including its AST).
std::string latexQuery(std::string_view doOperatorPrefix="do(", std::string_view doOperatorSuffix=")") const
Generates a LaTeX representation of the original query, e.g., P(Y | do(X), Z).
A causal model pairing a causal DAG with an optional observational BayesNet.
Definition causalModel.h:96
NodeId idFromName(std::string_view name) const
Node id from variable name (observed or latent).
Base class for dag.
Definition DAG.h:121
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.
bool existsNode(const NodeId id) const
returns true iff the NodeGraphPart contains the given nodeId
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
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
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
STL namespace.