61 template < GUM_Numeric GUM_SCALAR >
63 DAG g = bn.internalDag();
64 for (
auto id: g.nodes())
65 g.setName(
id, bn.variable(
id).name());
74 template < GUM_Numeric GUM_SCALAR >
81 template < GUM_Numeric GUM_SCALAR >
86 template < GUM_Numeric GUM_SCALAR >
93 for (
const auto& [latent,
children]: latentVarsDescriptor) {
100 template < GUM_Numeric GUM_SCALAR >
108 template < GUM_Numeric GUM_SCALAR >
116 template < GUM_Numeric GUM_SCALAR >
121 for (
auto id: dag.
nodes()) {
122 if (!dag.hasName(id)) {
123 GUM_ERROR(InvalidArgument,
124 "CausalModel: every node of the DAG must have a name (node " + std::to_string(id)
128 for (
const auto& [latent, children]: latentVarsDescriptor) {
129 addLatentVariable(latent, children, assumeNonSpurious);
131 GUM_CONSTRUCTOR(CausalModel)
138 template < GUM_Numeric GUM_SCALAR >
140 std::string_view latentName,
141 const std::vector< std::string >& childrenOfLatent,
143 std::vector< NodeId > childIds;
144 childIds.reserve(childrenOfLatent.size());
145 for (
const auto& nm: childrenOfLatent) {
151 template < GUM_Numeric GUM_SCALAR >
153 const std::vector< NodeId >& childrenOfLatent,
156 if (childrenOfLatent.size() < 2) {
161 if (
_observedDAG_.idFromName(std::string(latentName)).has_value()) {
163 "Latent variable name conflicts with an observed variable: "
164 + std::string(latentName));
166 if (_ids_names_.existsSecond(std::string(latentName))) {
168 "Latent variable name already used by another latent: " + std::string(latentName));
172 const NodeId id_latent = _causalDAG_.addNode();
175 _ids_names_.insert(id_latent, std::string(latentName));
178 for (
const auto& cid: childrenOfLatent) {
181 _causalDAG_.addArc(id_latent, cid);
185 if (!assumeNonSpurious) {
186 for (
auto i = childrenOfLatent.begin(); i != childrenOfLatent.end(); ++i) {
189 for (
auto jj = j; jj != childrenOfLatent.end(); ++jj) {
193 Arc ab(a, b), ba(b, a);
201 template < GUM_Numeric GUM_SCALAR >
206 template < GUM_Numeric GUM_SCALAR >
217 template < GUM_Numeric GUM_SCALAR >
221 latentIds.
insert(it.first());
226 template < GUM_Numeric GUM_SCALAR >
230 latentNames.
insert(it.second());
239 template < GUM_Numeric GUM_SCALAR >
244 "Arc(" + std::to_string(x) +
"," + std::to_string(y)
245 +
") not present in observationalBN");
251 template < GUM_Numeric GUM_SCALAR >
256 template < GUM_Numeric GUM_SCALAR >
261 "Arc(" + std::to_string(x) +
"," + std::to_string(y)
262 +
") not present in observationalBN");
265 if (!_causalDAG_.existsArc(
Arc(x, y))) { _causalDAG_.addArc(x, y); }
268 template < GUM_Numeric GUM_SCALAR >
273 template < GUM_Numeric GUM_SCALAR >
278 template < GUM_Numeric GUM_SCALAR >
293 template < GUM_Numeric GUM_SCALAR >
298 template < GUM_Numeric GUM_SCALAR >
303 if (subset.
empty()) {
317 for (
auto n: nodes) {
324 for (
const auto& a: causalDag.arcs()) {
325 const NodeId x = a.tail();
326 const NodeId y = a.head();
327 if (nodes.contains(x) && nodes.contains(y)) { sub.
addArc(x, y); }
333 std::vector< NodeId > mapped_children;
334 mapped_children.reserve(4);
338 if (nodes.contains(c)) mapped_children.push_back(c);
342 if (mapped_children.size() >= 2) {
343 latentDesc.emplace_back(cm.
nameFromId(L), std::move(mapped_children));
348 return CausalModel< GUM_SCALAR >(sub, latentDesc,
true);
355 template < GUM_Numeric GUM_SCALAR >
361 template < GUM_Numeric GUM_SCALAR >
366 template < GUM_Numeric GUM_SCALAR >
371 template < GUM_Numeric GUM_SCALAR >
380 template < GUM_Numeric GUM_SCALAR >
386 "CausalModel::backDoor: 'cause' and 'effect' must be observed (non-latent).");
390 if (candidates.empty())
return std::nullopt;
391 return candidates.front();
394 template < GUM_Numeric GUM_SCALAR >
400 "CausalModel::frontDoor: 'cause' and 'effect' must be observed (non-latent).");
404 if (candidates.empty())
return std::nullopt;
405 return candidates.front();
411 template < GUM_Numeric GUM_SCALAR >
416 template < GUM_Numeric GUM_SCALAR >
421 template < GUM_Numeric GUM_SCALAR >
425 const char* EDGE_COL)
const {
427 style.showLatentNames = SHOW_LATENT_NAMES;
428 if (EDGE_COL !=
nullptr) style.arcColor = EDGE_COL;
429 if (NODE_BG !=
nullptr) {
430 style.nodeBgColor = NODE_BG;
431 style.latentBgColor = NODE_BG;
433 if (NODE_FG !=
nullptr) {
434 style.nodeFgColor = NODE_FG;
435 style.latentFgColor = NODE_FG;
440 template < GUM_Numeric GUM_SCALAR >
447 const auto label = [
this](
NodeId n) {
450 }
catch (gum::NotFound&) {
return "L" + std::to_string(n); }
463 "(" + std::to_string(n) +
") " + label(n));
467 writer.
node(label(n), attributes);
473 writer.
node(label(n),
477 "(" + std::to_string(n) +
") " + label(n)));
489 writer.
edge(label(arc.tail()), label(arc.head()), attributes);
499 template < GUM_Numeric GUM_SCALAR >
512 template < GUM_Numeric GUM_SCALAR >
517 const auto opt =
_observedDAG_.idFromName(std::string(name));
518 if (!opt.has_value()) {
520 "CausalModel::idFromName: no observed or latent variable named '"
521 + std::string(name) +
"'.");
527 template < GUM_Numeric GUM_SCALAR >
536 template < GUM_Numeric GUM_SCALAR >
547 if (includeLatentVariables) {
549 result.
insert(iter.first(), iter.second());
560 template < GUM_Numeric GUM_SCALAR >
565 template < GUM_Numeric GUM_SCALAR >
569 "CausalModel::observationalBN: this model has no observational BayesNet "
570 "(built from a DAG).");
575 template < GUM_Numeric GUM_SCALAR >
583 template < GUM_Numeric GUM_SCALAR >
585 std::string_view effect)
const {
589 template < GUM_Numeric GUM_SCALAR >
591 std::string_view effect)
const {
595 template < GUM_Numeric GUM_SCALAR >
600 template < GUM_Numeric GUM_SCALAR >
The base class for all directed edges.
Class representing a Bayesian network.
void insert(const T1 &first, const T2 &second)
A causal model pairing a causal DAG with an optional observational BayesNet.
DAG causalDAG() const
Causal DAG (observed + latent variables), with node names set.
DAG _observedDAG_
Frozen copy of the observed DAG (never mutated after construction); names are set on it directly (set...
std::string _toDot_(const dot::CausalDotStyle &style, const dot::DotOptions &options) const
the dot of the causal DAG, with a look and options
void addLatentVariable(std::string_view latentName, const std::vector< std::string > &childrenOfLatent, bool assumeNonSpurious=false)
Add a latent variable by names of its observed children.
CausalModel< GUM_SCALAR > inducedCausalSubModel(const CausalModel< GUM_SCALAR > &cm, NodeSet subset) const
Induced causal submodel on a subset of nodes.
NodeProperty< NodeId > connectedComponents() const
Weakly connected components of the causal DAG.
bool hasObservationalBN() const noexcept
Whether this model was built from a BayesNet (CPTs available).
~CausalModel()
Destructor.
NodeSet latentVariablesIds() const
Node ids of all latent variables.
DAG _causalDAG_
The underlying DAG representing the causal structure (observed + latent).
bool isAssumedSpurious(NodeId x, NodeId y) const
Returns true if arc is present in observationalBN and absent in causalDAG.
Set< std::string > latentVariablesNames() const
Names of all latent variables.
std::optional< NodeSet > frontDoor(NodeId cause, NodeId effect) const
Find a frontdoor adjustment set (Z) between cause and effect (IDs only).
Bijection< NodeId, std::string > id2name(bool includeLatentVariable=false) const
Bidirectional mapping between node ids and variable names.
Bijection< NodeId, std::string > _ids_names_
Bidirectional mapping between node ids and variable names (latents only).
NodeId idFromName(std::string_view name) const
Node id from variable name (observed or latent).
std::string toDot() const
DOT representation of the causal DAG (observed + latent), with the look of the configuration.
bool existsArc(NodeId x, NodeId y) const
Whether a causal arc x → y exists (by ids) in the causal DAG.
std::string nameFromId(NodeId id) const
Variable name from node id (observed or latent).
NodeSet children(NodeId x) const
Children of a node (by id) in the causal DAG (including latents).
const DiscreteVariable & variable(NodeId id) const
From id to variable (observed only, by id).
CausalModel()=delete
Default constructor disabled: a causal model must be built from a BN.
Set< std::string > names() const
All variable names appearing in the causal model (observed + latent).
std::optional< BayesNet< GUM_SCALAR > > _observationalBN_
The observed Bayesian network, when the model was built with CPTs. Absent when built from a plain DAG...
void assumeNonSpurious(NodeId x, NodeId y)
Mark an arc as non-spurious: present in observationalBN, added to causalDAG.
std::optional< NodeSet > backDoor(NodeId cause, NodeId effect) const
Find a backdoor adjustment set (Z) between cause and effect (IDs only).
void assumeSpurious(NodeId x, NodeId y)
Mark an arc as spurious: present in observationalBN, removed from causalDAG.
NodeSet parents(NodeId x) const
Parents of a node (by id) in the causal DAG (including latents).
const BayesNet< GUM_SCALAR > & observationalBN() const
Observational BN (observed variables only).
void addArc(NodeId tail, NodeId head) final
insert a new arc into the directed graph
Base class for discrete random variable.
static NodeSetVec enumerateBackdoorSets(const DAG &dag, NodeId X, NodeId Y, const NodeSet &excluded_nodes=NodeSet(), std::size_t max_cardinality=0, bool only_minimal=true, bool stopAtFirst=false)
Enumerate valid backdoor adjustment sets.
static NodeSetVec enumerateFrontdoorSets(const DAG &dag, NodeId X, NodeId Y, const NodeSet &excluded_nodes=NodeSet(), std::size_t max_cardinality=0, bool only_minimal=true, bool stopAtFirst=false)
Enumerate valid frontdoor adjustment sets.
Exception: at least one argument passed to a function is not what was expected.
const NodeGraphPart & nodes() const
return *this as a NodeGraphPart
void setName(NodeId id, const std::string &name)
sets the name of node id
virtual void addNodeWithId(const NodeId id)
try to insert a node with the given id
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.
bool empty() const noexcept
Indicates whether the set is the empty set.
void insert(const Key &k)
Inserts a new element into the set.
void erase(const Key &k)
Erases an element from the set.
The options given to a toDot(const DotOptions&).
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
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.
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).
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).
Door criteria (backdoor/frontdoor) utilities for a DAG.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Size NodeId
Type for node ids.
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
GUM_SHARED_PUBLIC bool contains(std::string_view s, std::string_view needle)
true if needle in s
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,...
NodeProperty< NodeId > connectedComponents(const G &g)
Returns a node-to-component-id mapping for the (weakly) connected components of g.
gum is the global namespace for all aGrUM entities
std::vector< LatentDescriptorIds > LatentDescriptorVector
Collection of latent descriptors (see LatentDescriptorIds).
Generic node-reachability algorithms for aGrUM graphs.
The style of a causal model (section causal): nodeBgColor and nodeFgColor are the ones of the observe...
std::string latentBgColor
std::string latentFgColor
static CausalDotStyle read()
bool showLatentNames
show the names of the latent variables
The look shared by all the graphs: size, direction, layout, colors of the arcs and of the nodes.
std::string nodeBgColor
background color of the nodes
std::string arcColor
color of the arcs and edges, and of the border of the nodes