cai-causal-graph 0.5.0.dev0__tar.gz → 0.5.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/PKG-INFO +5 -8
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/README.md +1 -1
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/__init__.py +1 -1
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/causal_graph.py +82 -7
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/time_series_causal_graph.py +81 -93
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/pyproject.toml +4 -13
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/LICENSE +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/exceptions.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/graph_components.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/identify_utils.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/interfaces.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/metadata_handler.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/type_definitions.py +0 -0
- {cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/utils.py +0 -0
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: cai-causal-graph
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: A Causal AI package for causal graphs.
|
|
5
5
|
Home-page: https://causalgraph.causalens.com/
|
|
6
6
|
License: Apache-2.0
|
|
7
7
|
Author: causaLens
|
|
8
8
|
Author-email: opensource@causalens.com
|
|
9
|
-
Requires-Python: >=3.
|
|
9
|
+
Requires-Python: >=3.9.0,<3.13.0
|
|
10
10
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
13
12
|
Classifier: Programming Language :: Python :: 3.9
|
|
14
13
|
Classifier: Programming Language :: Python :: 3.10
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.11
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
17
16
|
Requires-Dist: mypy-extensions (>=1.0.0,<2.0.0)
|
|
18
|
-
Requires-Dist: networkx (>=3.0.0,<3.
|
|
19
|
-
Requires-Dist:
|
|
20
|
-
Requires-Dist: numpy (>=1.20.0,<1.25.0) ; python_full_version >= "3.8.0" and python_full_version < "3.9.0"
|
|
21
|
-
Requires-Dist: numpy (>=1.20.0,<2.0.0) ; python_full_version >= "3.9.0" and python_full_version < "3.13.0"
|
|
17
|
+
Requires-Dist: networkx (>=3.0.0,<3.3.0)
|
|
18
|
+
Requires-Dist: numpy (>=1.20.0,<2.0.0)
|
|
22
19
|
Requires-Dist: pandas (>=1.0.0,<3.0.0)
|
|
23
20
|
Project-URL: Documentation, https://causalgraph.causalens.com/
|
|
24
21
|
Project-URL: Repository, https://github.com/causalens/cai-causal-graph
|
|
@@ -45,7 +42,7 @@ Documentation, including a quickstart and code reference docs, can be found [her
|
|
|
45
42
|

|
|
46
43
|
|
|
47
44
|
> **Note**
|
|
48
|
-
> The current development cycle of this branch is `v0.
|
|
45
|
+
> The current development cycle of this branch is `v0.5.x` (stable).
|
|
49
46
|
|
|
50
47
|
## License
|
|
51
48
|
|
|
@@ -19,7 +19,7 @@ Documentation, including a quickstart and code reference docs, can be found [her
|
|
|
19
19
|

|
|
20
20
|
|
|
21
21
|
> **Note**
|
|
22
|
-
> The current development cycle of this branch is `v0.
|
|
22
|
+
> The current development cycle of this branch is `v0.5.x` (stable).
|
|
23
23
|
|
|
24
24
|
## License
|
|
25
25
|
|
|
@@ -18,7 +18,8 @@ from __future__ import annotations
|
|
|
18
18
|
import itertools
|
|
19
19
|
from collections import defaultdict
|
|
20
20
|
from copy import deepcopy
|
|
21
|
-
from
|
|
21
|
+
from functools import wraps
|
|
22
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Type, Union, cast
|
|
22
23
|
|
|
23
24
|
import networkx
|
|
24
25
|
import numpy
|
|
@@ -36,6 +37,22 @@ def to_list(var: Any) -> List[Any]:
|
|
|
36
37
|
return var if isinstance(var, list) else [var]
|
|
37
38
|
|
|
38
39
|
|
|
40
|
+
def reset_cached_attributes_decorator(func: Callable) -> Callable:
|
|
41
|
+
"""
|
|
42
|
+
Decorator to reset cached attributes of `cai_causal_graph.causal_graph.CausalGraph`.
|
|
43
|
+
|
|
44
|
+
Whenever a function is called that changes the graph, we need to reset these attributes.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
@wraps(func)
|
|
48
|
+
def wrapper(self: CausalGraph, *args, **kwargs) -> Any:
|
|
49
|
+
function = func(self, *args, **kwargs)
|
|
50
|
+
self._reset_cached_attributes()
|
|
51
|
+
return function
|
|
52
|
+
|
|
53
|
+
return wrapper
|
|
54
|
+
|
|
55
|
+
|
|
39
56
|
class Skeleton(CanDictSerialize, CanDictDeserialize):
|
|
40
57
|
"""A utility class to obtain the skeleton of the causal graph including nodes, edges and adjacency matrix."""
|
|
41
58
|
|
|
@@ -471,6 +488,13 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
471
488
|
|
|
472
489
|
super(HasIdentifier, self).__init__(meta=meta)
|
|
473
490
|
|
|
491
|
+
# cached attributes
|
|
492
|
+
self._is_dag: Optional[bool] = None
|
|
493
|
+
self._networkx: Optional[networkx.Graph] = None
|
|
494
|
+
self._is_fully_directed_cached: Optional[bool] = None
|
|
495
|
+
self._is_fully_undirected_cached: Optional[bool] = None
|
|
496
|
+
self._adjacency: Optional[numpy.ndarray] = None
|
|
497
|
+
|
|
474
498
|
def __copy__(self) -> CausalGraph:
|
|
475
499
|
"""Copy a `cai_causal_graph.causal_graph.CausalGraph` instance."""
|
|
476
500
|
return self.copy()
|
|
@@ -570,6 +594,9 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
570
594
|
The column order is dependent upon the ordering of node names. To obtain both, adjacency matrix and node names
|
|
571
595
|
in corresponding order use the to_numpy method instead.
|
|
572
596
|
"""
|
|
597
|
+
if self._adjacency is not None:
|
|
598
|
+
return deepcopy(self._adjacency)
|
|
599
|
+
|
|
573
600
|
# check that the graph only has directed and undirected edges
|
|
574
601
|
nodes_indices_map = {node: i for i, node in enumerate(self.get_node_names())}
|
|
575
602
|
adj = numpy.zeros((len(self.nodes), len(self.nodes)), dtype=int)
|
|
@@ -585,7 +612,8 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
585
612
|
f'Adjacency matrices can only be computed if the CausalGraph instance solely contains directed and '
|
|
586
613
|
f'undirected edges. Got {edge.get_edge_type()} for the edge {edge.descriptor}.'
|
|
587
614
|
)
|
|
588
|
-
|
|
615
|
+
self._adjacency = adj
|
|
616
|
+
return self._adjacency
|
|
589
617
|
|
|
590
618
|
@property
|
|
591
619
|
def sepsets(self) -> dict:
|
|
@@ -614,12 +642,26 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
614
642
|
|
|
615
643
|
def is_dag(self) -> bool:
|
|
616
644
|
"""Check whether the `cai_causal_graph.causal_graph.CausalGraph` instance is a Directed Acyclic Graph (DAG)."""
|
|
617
|
-
|
|
645
|
+
if self._is_dag is None:
|
|
646
|
+
self._is_dag = (
|
|
647
|
+
networkx.is_directed_acyclic_graph(self.to_networkx()) if self._is_fully_directed() else False
|
|
648
|
+
)
|
|
649
|
+
return self._is_dag
|
|
618
650
|
|
|
619
651
|
def is_empty(self) -> bool:
|
|
620
652
|
"""Return True if there are no nodes and edges. False otherwise."""
|
|
621
653
|
return len(self.nodes) == 0 and len(self.edges) == 0
|
|
622
654
|
|
|
655
|
+
@property
|
|
656
|
+
def has_non_serializable_metadata(self) -> bool:
|
|
657
|
+
"""
|
|
658
|
+
Return `True` whether the graph or any node or edge contains non-JSON serializable metadata.
|
|
659
|
+
|
|
660
|
+
By default, this returns `False`. Please note that by default `CausalGraph` does not perform any checks
|
|
661
|
+
on the metadata. Instead, this method enables any derived classes to implement custom checks.
|
|
662
|
+
"""
|
|
663
|
+
return False
|
|
664
|
+
|
|
623
665
|
def _check_node_exists(self, identifier: NodeLike) -> str:
|
|
624
666
|
"""Validate and return the node identifier."""
|
|
625
667
|
identifier = self._NodeCls.identifier_from(identifier)
|
|
@@ -709,14 +751,20 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
709
751
|
Check whether the `cai_causal_graph.causal_graph.CausalGraph` instance only contains directed edges, i.e.,
|
|
710
752
|
all edges are directed.
|
|
711
753
|
"""
|
|
712
|
-
|
|
754
|
+
if self._is_fully_directed_cached is None:
|
|
755
|
+
self._is_fully_directed_cached = all(edge.get_edge_type() == EdgeType.DIRECTED_EDGE for edge in self.edges)
|
|
756
|
+
return self._is_fully_directed_cached
|
|
713
757
|
|
|
714
758
|
def _is_fully_undirected(self) -> bool:
|
|
715
759
|
"""
|
|
716
760
|
Check whether the `cai_causal_graph.causal_graph.CausalGraph` instance only contains undirected edges, i.e.,
|
|
717
761
|
all edges are undirected.
|
|
718
762
|
"""
|
|
719
|
-
|
|
763
|
+
if self._is_fully_undirected_cached is None:
|
|
764
|
+
self._is_fully_undirected_cached = all(
|
|
765
|
+
edge.get_edge_type() == EdgeType.UNDIRECTED_EDGE for edge in self.edges
|
|
766
|
+
)
|
|
767
|
+
return self._is_fully_undirected_cached
|
|
720
768
|
|
|
721
769
|
def _is_directed_and_or_undirected_error_message(self, is_one_kind_only: bool = True) -> str:
|
|
722
770
|
"""
|
|
@@ -823,6 +871,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
823
871
|
except KeyError:
|
|
824
872
|
return False
|
|
825
873
|
|
|
874
|
+
@reset_cached_attributes_decorator
|
|
826
875
|
def add_node(
|
|
827
876
|
self,
|
|
828
877
|
/,
|
|
@@ -868,6 +917,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
868
917
|
|
|
869
918
|
return node
|
|
870
919
|
|
|
920
|
+
@reset_cached_attributes_decorator
|
|
871
921
|
def add_nodes_from(self, identifiers: List[NodeLike]):
|
|
872
922
|
"""
|
|
873
923
|
A convenience method to add multiple nodes. Only allows to set up nodes with default setup.
|
|
@@ -878,12 +928,14 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
878
928
|
for identifier in identifiers:
|
|
879
929
|
self.add_node(identifier)
|
|
880
930
|
|
|
931
|
+
@reset_cached_attributes_decorator
|
|
881
932
|
def add_fully_connected_nodes(self, inputs: List[NodeLike], outputs: List[NodeLike]):
|
|
882
933
|
"""Create directed edges between all inputs and all outputs."""
|
|
883
934
|
for input_node in inputs:
|
|
884
935
|
for output_node in outputs:
|
|
885
936
|
self.add_edge(input_node, output_node, edge_type=EdgeType.DIRECTED_EDGE)
|
|
886
937
|
|
|
938
|
+
@reset_cached_attributes_decorator
|
|
887
939
|
def delete_node(self, identifier: NodeLike):
|
|
888
940
|
"""
|
|
889
941
|
Delete a node from the causal graph. This also deletes all edges connecting to this node.
|
|
@@ -905,6 +957,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
905
957
|
self._nodes_by_identifier.pop(identifier)
|
|
906
958
|
node.invalidate()
|
|
907
959
|
|
|
960
|
+
@reset_cached_attributes_decorator
|
|
908
961
|
def remove_node(self, identifier: NodeLike):
|
|
909
962
|
"""
|
|
910
963
|
Remove a node from the causal graph. This also deletes all edges connecting to this node.
|
|
@@ -913,6 +966,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
913
966
|
"""
|
|
914
967
|
self.delete_node(identifier=identifier)
|
|
915
968
|
|
|
969
|
+
@reset_cached_attributes_decorator
|
|
916
970
|
def replace_node(
|
|
917
971
|
self,
|
|
918
972
|
/,
|
|
@@ -1111,6 +1165,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1111
1165
|
"""Return all edge pairs in the current graph."""
|
|
1112
1166
|
return [edge.get_edge_pair() for edge in self.edges]
|
|
1113
1167
|
|
|
1168
|
+
@reset_cached_attributes_decorator
|
|
1114
1169
|
def change_edge_type(self, source: NodeLike, destination: NodeLike, new_edge_type: EdgeType):
|
|
1115
1170
|
"""
|
|
1116
1171
|
Change an edge type for a specific edge.
|
|
@@ -1133,6 +1188,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1133
1188
|
self.remove_edge(source=source, destination=destination, edge_type=edge.get_edge_type())
|
|
1134
1189
|
self.add_edge(source=source, destination=destination, edge_type=new_edge_type, meta=meta)
|
|
1135
1190
|
|
|
1191
|
+
@reset_cached_attributes_decorator
|
|
1136
1192
|
def add_edge(
|
|
1137
1193
|
self,
|
|
1138
1194
|
/,
|
|
@@ -1196,6 +1252,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1196
1252
|
self._set_edge(edge=edge, validate=validate)
|
|
1197
1253
|
return edge
|
|
1198
1254
|
|
|
1255
|
+
@reset_cached_attributes_decorator
|
|
1199
1256
|
def add_edges_from(self, pairs: List[Tuple[NodeLike, NodeLike]], validate: bool = True):
|
|
1200
1257
|
"""
|
|
1201
1258
|
A convenience method to add multiple edges by specifying tuples of source and destination node identifiers.
|
|
@@ -1214,6 +1271,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1214
1271
|
validate_pair_type(pair)
|
|
1215
1272
|
self.add_edge(source=pair[0], destination=pair[1], validate=validate)
|
|
1216
1273
|
|
|
1274
|
+
@reset_cached_attributes_decorator
|
|
1217
1275
|
def add_edges_from_paths(self, paths: Union[List[NodeLike], List[List[NodeLike]]], validate: bool = True):
|
|
1218
1276
|
"""
|
|
1219
1277
|
A convenience method to add multiple edges by specifying a single or a list of paths.
|
|
@@ -1252,6 +1310,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1252
1310
|
validate_pair_type((source, destination))
|
|
1253
1311
|
self.add_edge(source=source, destination=destination, validate=validate)
|
|
1254
1312
|
|
|
1313
|
+
@reset_cached_attributes_decorator
|
|
1255
1314
|
def add_edge_by_pair(
|
|
1256
1315
|
self,
|
|
1257
1316
|
pair: Tuple[NodeLike, NodeLike],
|
|
@@ -1274,11 +1333,13 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1274
1333
|
validate_pair_type(pair)
|
|
1275
1334
|
self.add_edge(pair[0], pair[1], edge_type=edge_type, meta=meta, validate=validate)
|
|
1276
1335
|
|
|
1336
|
+
@reset_cached_attributes_decorator
|
|
1277
1337
|
def remove_edge_by_pair(self, pair: Tuple[NodeLike, NodeLike], edge_type: Optional[EdgeType] = None):
|
|
1278
1338
|
"""Remove edge by pair identifier (source, destination)."""
|
|
1279
1339
|
validate_pair_type(pair)
|
|
1280
1340
|
self.delete_edge(pair[0], pair[1], edge_type=edge_type)
|
|
1281
1341
|
|
|
1342
|
+
@reset_cached_attributes_decorator
|
|
1282
1343
|
def delete_edge(self, /, source: NodeLike, destination: NodeLike, *, edge_type: Optional[EdgeType] = None):
|
|
1283
1344
|
"""
|
|
1284
1345
|
Delete an edge from the causal graph.
|
|
@@ -1321,10 +1382,12 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1321
1382
|
self._clean_empty_edge_dictionaries()
|
|
1322
1383
|
edge.invalidate()
|
|
1323
1384
|
|
|
1385
|
+
@reset_cached_attributes_decorator
|
|
1324
1386
|
def remove_edge(self, /, source: NodeLike, destination: NodeLike, *, edge_type: Optional[EdgeType] = None):
|
|
1325
1387
|
"""Remove a specific edge by source and destination node identifiers, as well as edge type."""
|
|
1326
1388
|
self.delete_edge(source=source, destination=destination, edge_type=edge_type)
|
|
1327
1389
|
|
|
1390
|
+
@reset_cached_attributes_decorator
|
|
1328
1391
|
def replace_edge(
|
|
1329
1392
|
self,
|
|
1330
1393
|
/,
|
|
@@ -1910,7 +1973,8 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1910
1973
|
of directed and undirected edges or there are more elaborate edge types, a
|
|
1911
1974
|
`cai_causal_graph.exceptions.CausalGraphErrors.GraphConversionError` will be raised.
|
|
1912
1975
|
"""
|
|
1913
|
-
|
|
1976
|
+
if self._networkx is not None:
|
|
1977
|
+
return deepcopy(self._networkx)
|
|
1914
1978
|
# Save these off as they need to be called more than once.
|
|
1915
1979
|
is_fully_directed = self._is_fully_directed()
|
|
1916
1980
|
is_fully_undirected = self._is_fully_undirected()
|
|
@@ -1942,6 +2006,8 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
1942
2006
|
for target in destinations.keys():
|
|
1943
2007
|
networkx_graph.add_edge(source, target)
|
|
1944
2008
|
|
|
2009
|
+
self._networkx = networkx_graph
|
|
2010
|
+
|
|
1945
2011
|
return networkx_graph
|
|
1946
2012
|
|
|
1947
2013
|
def to_numpy(self) -> Tuple[numpy.ndarray, List[str]]:
|
|
@@ -2101,10 +2167,19 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
|
|
|
2101
2167
|
assert isinstance(new_graph, self.__class__) # for linting and sanity check
|
|
2102
2168
|
return new_graph
|
|
2103
2169
|
|
|
2170
|
+
def _reset_cached_attributes(self):
|
|
2171
|
+
"""Reset cached internal attributes."""
|
|
2172
|
+
self._is_dag = None
|
|
2173
|
+
self._networkx = None
|
|
2174
|
+
self._is_fully_directed_cached = None
|
|
2175
|
+
self._is_fully_undirected_cached = None
|
|
2176
|
+
self._adjacency = None
|
|
2177
|
+
|
|
2104
2178
|
def __repr__(self) -> str:
|
|
2105
2179
|
"""Return a string description of the `cai_causal_graph.causal_graph.CausalGraph` instance."""
|
|
2106
2180
|
return (
|
|
2107
|
-
f'{self.__class__.__name__}(num_nodes={len(self.nodes)}, num_edges={len(self.edges)},
|
|
2181
|
+
f'{self.__class__.__name__}(num_nodes={len(self.nodes)}, num_edges={len(self.edges)}, '
|
|
2182
|
+
f'id={self.__hash__()}, is_dag={self.is_dag()})'
|
|
2108
2183
|
f'\n'
|
|
2109
2184
|
f'Nodes: {self.nodes}\nEdges: {self.edges}'
|
|
2110
2185
|
)
|
{cai_causal_graph-0.5.0.dev0 → cai_causal_graph-0.5.2}/cai_causal_graph/time_series_causal_graph.py
RENAMED
|
@@ -19,14 +19,13 @@ from __future__ import annotations
|
|
|
19
19
|
import logging
|
|
20
20
|
from collections import defaultdict
|
|
21
21
|
from copy import deepcopy
|
|
22
|
-
from
|
|
23
|
-
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
|
|
22
|
+
from typing import Callable, Dict, List, Optional, Tuple, Type, Union, cast
|
|
24
23
|
|
|
25
24
|
import networkx
|
|
26
25
|
import numpy
|
|
27
26
|
from mypy_extensions import Arg, DefaultArg
|
|
28
27
|
|
|
29
|
-
from cai_causal_graph import CausalGraph, Skeleton
|
|
28
|
+
from cai_causal_graph.causal_graph import CausalGraph, Skeleton, reset_cached_attributes_decorator
|
|
30
29
|
from cai_causal_graph.graph_components import Edge, TimeSeriesEdge, TimeSeriesNode
|
|
31
30
|
from cai_causal_graph.interfaces import HasIdentifier, HasMetadata
|
|
32
31
|
from cai_causal_graph.type_definitions import TIME_LAG, EdgeType, NodeLike, NodeVariableType
|
|
@@ -35,26 +34,6 @@ from cai_causal_graph.utils import get_name_with_lag, get_variable_name_and_lag
|
|
|
35
34
|
logger = logging.getLogger(__name__)
|
|
36
35
|
|
|
37
36
|
|
|
38
|
-
def _reset_ts_graph_attributes(func: Callable) -> Callable:
|
|
39
|
-
"""
|
|
40
|
-
Decorator to reset attributes of TimeSeriesCausalGraph such as summary graph, minimal graph, etc.
|
|
41
|
-
|
|
42
|
-
Whenever a function is called that changes the graph, we need to reset these attributes.
|
|
43
|
-
"""
|
|
44
|
-
|
|
45
|
-
# TODO - CAUSALAI-3369: Improve this decorator to remove need to reset the summary graph and other attributes
|
|
46
|
-
@wraps(func)
|
|
47
|
-
def wrapper(self: TimeSeriesCausalGraph, *args, **kwargs) -> Any:
|
|
48
|
-
function = func(self, *args, **kwargs)
|
|
49
|
-
self._minimal_graph = None
|
|
50
|
-
self._summary_graph = None
|
|
51
|
-
self._stationary_graph = None
|
|
52
|
-
self._variables = None
|
|
53
|
-
return function
|
|
54
|
-
|
|
55
|
-
return wrapper
|
|
56
|
-
|
|
57
|
-
|
|
58
37
|
class TimeSeriesCausalGraph(CausalGraph):
|
|
59
38
|
"""
|
|
60
39
|
A causal graph for time series data.
|
|
@@ -143,9 +122,8 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
143
122
|
|
|
144
123
|
# list of variables in the graph, i.e. discarding the lags (X1(t-1) and X1 are the same variable)
|
|
145
124
|
self._variables: Optional[List[str]] = None
|
|
146
|
-
self.
|
|
147
|
-
self.
|
|
148
|
-
self._minimal_graph: Optional[TimeSeriesCausalGraph] = None
|
|
125
|
+
self._is_minimal_graph: Optional[bool] = None
|
|
126
|
+
self._is_stationary_graph: Optional[bool] = None
|
|
149
127
|
|
|
150
128
|
def is_stationary_graph(self) -> bool:
|
|
151
129
|
"""
|
|
@@ -159,10 +137,13 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
159
137
|
logger.warning('The graph is not a DAG. The stationarity check is not valid.')
|
|
160
138
|
return False
|
|
161
139
|
|
|
162
|
-
|
|
140
|
+
if self._is_stationary_graph is None:
|
|
141
|
+
stationary_graph = self.get_stationary_graph()
|
|
163
142
|
|
|
164
|
-
|
|
165
|
-
|
|
143
|
+
# now check if the stationary graph is equal to the current graph
|
|
144
|
+
self._is_stationary_graph = stationary_graph == self
|
|
145
|
+
|
|
146
|
+
return self._is_stationary_graph
|
|
166
147
|
|
|
167
148
|
def get_stationary_graph(self) -> TimeSeriesCausalGraph:
|
|
168
149
|
"""
|
|
@@ -170,9 +151,6 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
170
151
|
|
|
171
152
|
If there exists the edge `X(t-1) -> X(t)`, then there must be the edge `X(t-2) -> X(t-1)`, etc.
|
|
172
153
|
"""
|
|
173
|
-
if self._stationary_graph is not None:
|
|
174
|
-
return self._stationary_graph
|
|
175
|
-
|
|
176
154
|
# extract the minimal graph
|
|
177
155
|
minimal_graph = self.get_minimal_graph()
|
|
178
156
|
|
|
@@ -181,9 +159,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
181
159
|
neg_lag, pos_lag = lags[0], lags[-1]
|
|
182
160
|
|
|
183
161
|
# now extend the minimal graph to the current max and min lag to match the current graph
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
return self._stationary_graph
|
|
162
|
+
return minimal_graph.extend_graph(-neg_lag, pos_lag, include_all_parents=False)
|
|
187
163
|
|
|
188
164
|
def get_minimal_graph(self) -> TimeSeriesCausalGraph:
|
|
189
165
|
"""
|
|
@@ -349,7 +325,10 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
349
325
|
|
|
350
326
|
See `cai_causal_graph.time_series_causal_graph.TimeSeriesCausalGraph.get_minimal_graph` for more details.
|
|
351
327
|
"""
|
|
352
|
-
|
|
328
|
+
if self._is_minimal_graph is None:
|
|
329
|
+
self._is_minimal_graph = self == self.get_minimal_graph()
|
|
330
|
+
|
|
331
|
+
return self._is_minimal_graph
|
|
353
332
|
|
|
354
333
|
def get_summary_graph(self) -> CausalGraph:
|
|
355
334
|
"""
|
|
@@ -367,63 +346,58 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
367
346
|
|
|
368
347
|
:return: The summary graph as a `cai_causal_graph.causal_graph.CausalGraph` object.
|
|
369
348
|
"""
|
|
370
|
-
if
|
|
371
|
-
|
|
372
|
-
# now check as described above (assume edges are already directed)
|
|
373
|
-
edges = self.get_edges()
|
|
374
|
-
|
|
375
|
-
# check if the graph is a DAG
|
|
376
|
-
assert self.is_dag(), 'This method only works for DAGs but the current graph is not a DAG.'
|
|
377
|
-
|
|
378
|
-
for edge in edges:
|
|
379
|
-
# first we need to extract the variable names from the nodes as the summary graph
|
|
380
|
-
# will have the variable names as nodes
|
|
381
|
-
source_node = edge.source
|
|
382
|
-
destination_node = edge.destination
|
|
383
|
-
assert isinstance(source_node, TimeSeriesNode)
|
|
384
|
-
assert isinstance(destination_node, TimeSeriesNode)
|
|
385
|
-
|
|
386
|
-
source_variable_name = source_node.variable_name
|
|
387
|
-
destination_variable_name = destination_node.variable_name
|
|
388
|
-
|
|
389
|
-
assert (
|
|
390
|
-
source_variable_name is not None
|
|
391
|
-
), 'Source variable name is None, cannot create summary graph. The edge is: {}'.format(edge)
|
|
392
|
-
|
|
393
|
-
assert (
|
|
394
|
-
destination_variable_name is not None
|
|
395
|
-
), 'Destination variable name is None, cannot create summary graph. The edge is: {}'.format(edge)
|
|
396
|
-
|
|
397
|
-
if source_variable_name != destination_variable_name and not summary_graph.is_edge_by_pair(
|
|
398
|
-
(source_variable_name, destination_variable_name)
|
|
399
|
-
):
|
|
400
|
-
# create the nodes
|
|
401
|
-
source = self._NodeCls(
|
|
402
|
-
identifier=source_variable_name,
|
|
403
|
-
meta=source_node.meta,
|
|
404
|
-
variable_type=source_node.variable_type,
|
|
405
|
-
)
|
|
406
|
-
destination = self._NodeCls(
|
|
407
|
-
identifier=destination_variable_name,
|
|
408
|
-
meta=destination_node.meta,
|
|
409
|
-
variable_type=destination_node.variable_type,
|
|
410
|
-
)
|
|
349
|
+
# check if the graph is a DAG
|
|
350
|
+
assert self.is_dag(), 'This method only works for DAGs but the current graph is not a DAG.'
|
|
411
351
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
352
|
+
summary_graph = self._SummaryGraphCls(meta=deepcopy(self.meta))
|
|
353
|
+
# now check as described above (assume edges are already directed)
|
|
354
|
+
edges = self.get_edges()
|
|
355
|
+
|
|
356
|
+
for edge in edges:
|
|
357
|
+
# first we need to extract the variable names from the nodes as the summary graph
|
|
358
|
+
# will have the variable names as nodes
|
|
359
|
+
source_node = edge.source
|
|
360
|
+
destination_node = edge.destination
|
|
361
|
+
assert isinstance(source_node, TimeSeriesNode)
|
|
362
|
+
assert isinstance(destination_node, TimeSeriesNode)
|
|
363
|
+
|
|
364
|
+
source_variable_name = source_node.variable_name
|
|
365
|
+
destination_variable_name = destination_node.variable_name
|
|
417
366
|
|
|
418
|
-
|
|
367
|
+
assert (
|
|
368
|
+
source_variable_name is not None
|
|
369
|
+
), 'Source variable name is None, cannot create summary graph. The edge is: {}'.format(edge)
|
|
419
370
|
|
|
420
|
-
|
|
371
|
+
assert (
|
|
372
|
+
destination_variable_name is not None
|
|
373
|
+
), 'Destination variable name is None, cannot create summary graph. The edge is: {}'.format(edge)
|
|
374
|
+
|
|
375
|
+
if source_variable_name != destination_variable_name and not summary_graph.is_edge_by_pair(
|
|
376
|
+
(source_variable_name, destination_variable_name)
|
|
377
|
+
):
|
|
378
|
+
# create the nodes
|
|
379
|
+
source = self._NodeCls(
|
|
380
|
+
identifier=source_variable_name,
|
|
381
|
+
meta=source_node.meta,
|
|
382
|
+
variable_type=source_node.variable_type,
|
|
383
|
+
)
|
|
384
|
+
destination = self._NodeCls(
|
|
385
|
+
identifier=destination_variable_name,
|
|
386
|
+
meta=destination_node.meta,
|
|
387
|
+
variable_type=destination_node.variable_type,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
# create the edge
|
|
391
|
+
edge = self._EdgeCls(source=source, destination=destination, edge_type=edge.edge_type, meta=edge.meta)
|
|
392
|
+
summary_graph.add_edge(edge=edge)
|
|
393
|
+
|
|
394
|
+
return summary_graph
|
|
421
395
|
|
|
422
396
|
def extend_graph(
|
|
423
397
|
self,
|
|
424
398
|
backward_steps: Optional[int] = None,
|
|
425
399
|
forward_steps: Optional[int] = None,
|
|
426
|
-
include_all_parents: bool =
|
|
400
|
+
include_all_parents: bool = True,
|
|
427
401
|
) -> TimeSeriesCausalGraph:
|
|
428
402
|
"""
|
|
429
403
|
Return an extended graph.
|
|
@@ -435,6 +409,11 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
435
409
|
include nodes at time t-2, but rather that it will include nodes at time t-2 and all the nodes that are
|
|
436
410
|
connected to them as specified by the minimal graph.
|
|
437
411
|
|
|
412
|
+
By default, this will also add all parents of newly added nodes. This is done to ensure that all nodes
|
|
413
|
+
corresponding to the same variable name have consistent parents, which is particularly useful for
|
|
414
|
+
causal modeling tasks. This can be controlled by the `include_all_parents` parameter. If set to `False`, then
|
|
415
|
+
only nodes up-to `backward_steps` back in time are added.
|
|
416
|
+
|
|
438
417
|
If both `backward_steps` and `forward_steps` are None, the original graph is returned.
|
|
439
418
|
|
|
440
419
|
:param backward_steps: Number of steps to extend the graph backwards in time. If None, do not extend backwards.
|
|
@@ -442,9 +421,11 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
442
421
|
:param include_all_parents: If `True`, any nodes and edges required to predict nodes up to `backward_steps` ago
|
|
443
422
|
will also be added, in addition to the nodes/edges normally added by this method. This may mean that nodes
|
|
444
423
|
further back in time than `backward_steps` will be added, if they are parents of any nodes up to
|
|
445
|
-
`backward_steps` ago. Default is `
|
|
424
|
+
`backward_steps` ago. Default is `True`, meaning this extra nodes/edges are added.
|
|
425
|
+
|
|
446
426
|
`include_all_parents` is only valid when specifying a `backward_steps`, and will have no effect on the
|
|
447
|
-
logic of `forward_steps
|
|
427
|
+
logic of `forward_steps` since by definition all the parents of the added nodes in the future will either
|
|
428
|
+
already exist in the minimal graph or be added.
|
|
448
429
|
:return: Extended graph with nodes for each variable at each time step from `backward_steps` to `forward_steps`.
|
|
449
430
|
"""
|
|
450
431
|
# check steps are valid (positive integers) if not None
|
|
@@ -596,7 +577,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
596
577
|
"""
|
|
597
578
|
return self.get_variable_names_from_node_names(node_names=self.get_node_names())
|
|
598
579
|
|
|
599
|
-
@
|
|
580
|
+
@reset_cached_attributes_decorator
|
|
600
581
|
def add_node(
|
|
601
582
|
self,
|
|
602
583
|
/,
|
|
@@ -662,7 +643,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
662
643
|
|
|
663
644
|
return node
|
|
664
645
|
|
|
665
|
-
@
|
|
646
|
+
@reset_cached_attributes_decorator
|
|
666
647
|
def replace_node(
|
|
667
648
|
self,
|
|
668
649
|
/,
|
|
@@ -700,7 +681,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
700
681
|
|
|
701
682
|
super().replace_node(node_id=node_id, new_node_id=new_node_id, variable_type=variable_type, meta=meta)
|
|
702
683
|
|
|
703
|
-
@
|
|
684
|
+
@reset_cached_attributes_decorator
|
|
704
685
|
def delete_node(self, identifier: NodeLike):
|
|
705
686
|
"""
|
|
706
687
|
Delete a node from the graph.
|
|
@@ -712,7 +693,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
712
693
|
self._remove_node_from_cache(node)
|
|
713
694
|
super().delete_node(identifier)
|
|
714
695
|
|
|
715
|
-
@
|
|
696
|
+
@reset_cached_attributes_decorator
|
|
716
697
|
def delete_edge(self, /, source: NodeLike, destination: NodeLike, *, edge_type: Optional[EdgeType] = None):
|
|
717
698
|
"""
|
|
718
699
|
Delete an edge from the graph.
|
|
@@ -778,7 +759,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
778
759
|
)
|
|
779
760
|
# No else needed as we don't need to check time direction for other edge types.
|
|
780
761
|
|
|
781
|
-
@
|
|
762
|
+
@reset_cached_attributes_decorator
|
|
782
763
|
def add_time_edge(
|
|
783
764
|
self,
|
|
784
765
|
/,
|
|
@@ -1071,7 +1052,7 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
1071
1052
|
assert node.variable_name is not None
|
|
1072
1053
|
variables.append(node.variable_name)
|
|
1073
1054
|
self._variables = sorted(list(set(variables)))
|
|
1074
|
-
return self._variables
|
|
1055
|
+
return self._variables.copy()
|
|
1075
1056
|
|
|
1076
1057
|
def to_numpy_by_lag(self) -> Tuple[Dict[int, numpy.ndarray], List[str]]:
|
|
1077
1058
|
"""
|
|
@@ -1179,3 +1160,10 @@ class TimeSeriesCausalGraph(CausalGraph):
|
|
|
1179
1160
|
meta=node.meta, # meta is shallow copied by the node constructor
|
|
1180
1161
|
variable_type=node.variable_type,
|
|
1181
1162
|
)
|
|
1163
|
+
|
|
1164
|
+
def _reset_cached_attributes(self):
|
|
1165
|
+
"""Reset cached internal attributes."""
|
|
1166
|
+
self._variables = None
|
|
1167
|
+
self._is_minimal_graph = None
|
|
1168
|
+
self._is_stationary_graph = None
|
|
1169
|
+
super()._reset_cached_attributes()
|
|
@@ -42,7 +42,7 @@ cache_dir = '/dev/null'
|
|
|
42
42
|
|
|
43
43
|
[tool.poetry]
|
|
44
44
|
name = "cai-causal-graph"
|
|
45
|
-
version = "0.5.
|
|
45
|
+
version = "0.5.2"
|
|
46
46
|
description = "A Causal AI package for causal graphs."
|
|
47
47
|
license = "Apache-2.0"
|
|
48
48
|
authors = ["causaLens <opensource@causalens.com>"]
|
|
@@ -55,19 +55,10 @@ packages = [{include = "cai_causal_graph"}]
|
|
|
55
55
|
[tool.poetry.dependencies]
|
|
56
56
|
mypy-extensions = "^1.0.0"
|
|
57
57
|
# networkx 3.3 broke how get_all_simple_paths works so want to bound for now.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
{version = ">=3.0.0, <3.3.0", python = ">=3.9.0, <3.13.0"},
|
|
61
|
-
{version = ">=3.0.0, <3.2.0", python = ">=3.8.0, <3.9.0"} # 3.1 is the last version to support 3.8.
|
|
62
|
-
]
|
|
63
|
-
# Newest numpy is >= 3.9 so need to have different deps while we still support 3.8 but will drop 3.8 on next minor.
|
|
64
|
-
# 1.26 is the first version to support 3.12, but want to allow other versions to support earlier numpy.
|
|
65
|
-
numpy = [
|
|
66
|
-
{version = "^1.20.0", python = ">=3.9.0, <3.13.0"},
|
|
67
|
-
{version = ">=1.20.0, <1.25.0", python = ">=3.8.0, <3.9.0"} # 1.24 is the last version to support 3.8.
|
|
68
|
-
]
|
|
58
|
+
networkx = ">=3.0.0, <3.3.0"
|
|
59
|
+
numpy = "^1.20.0"
|
|
69
60
|
pandas = ">=1.0.0, <3.0.0"
|
|
70
|
-
python = ">=3.
|
|
61
|
+
python = ">=3.9.0, <3.13.0"
|
|
71
62
|
|
|
72
63
|
[tool.poetry.dev-dependencies]
|
|
73
64
|
bandit = "^1.7.5"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|