cai-causal-graph 0.4.6.dev0__tar.gz → 0.4.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cai-causal-graph
3
- Version: 0.4.6.dev0
3
+ Version: 0.4.7
4
4
  Summary: A Causal AI package for causal graphs.
5
5
  Home-page: https://causalgraph.causalens.com/
6
6
  License: Apache-2.0
@@ -15,7 +15,8 @@ Classifier: Programming Language :: Python :: 3.10
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Requires-Dist: mypy-extensions (>=1.0.0,<2.0.0)
18
- Requires-Dist: networkx (>=3.0.0,<4.0.0)
18
+ Requires-Dist: networkx (>=3.0.0,<3.2.0) ; python_full_version >= "3.8.0" and python_full_version < "3.9.0"
19
+ Requires-Dist: networkx (>=3.0.0,<3.3.0) ; python_full_version >= "3.9.0" and python_full_version < "3.13.0"
19
20
  Requires-Dist: numpy (>=1.20.0,<1.25.0) ; python_full_version >= "3.8.0" and python_full_version < "3.9.0"
20
21
  Requires-Dist: numpy (>=1.20.0,<2.0.0) ; python_full_version >= "3.9.0" and python_full_version < "3.13.0"
21
22
  Requires-Dist: pandas (>=1.0.0,<3.0.0)
@@ -31,7 +31,7 @@ __all__ = [
31
31
  'VARIABLE_NAME',
32
32
  ]
33
33
 
34
- __version__ = '0.4.6.dev0'
34
+ __version__ = '0.4.7'
35
35
 
36
36
  from cai_causal_graph.causal_graph import CausalGraph, Skeleton
37
37
  from cai_causal_graph.time_series_causal_graph import TimeSeriesCausalGraph
@@ -1797,6 +1797,12 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1797
1797
 
1798
1798
  assert all(node in self.get_node_names() for node in [source, destination])
1799
1799
 
1800
+ # In networkx 3.3 this will return a path of length 1 with just that node in it. We don't want to consider this
1801
+ # particularly as there is no self loop from that node to itself. One could make an edge from source to source
1802
+ # but then it would no longer be a DAG as we confirm in the first step of this method.
1803
+ if source == destination:
1804
+ return []
1805
+
1800
1806
  return list(networkx.all_simple_paths(self.to_networkx(), source, destination))
1801
1807
 
1802
1808
  def directed_path_exists(self, source: NodeLike, destination: NodeLike) -> bool:
@@ -13,6 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  """
16
+ from itertools import combinations
16
17
  from typing import List, Optional, Set, Tuple, Union
17
18
 
18
19
  import networkx
@@ -20,7 +21,7 @@ import networkx
20
21
  from cai_causal_graph import CausalGraph, Skeleton
21
22
  from cai_causal_graph.exceptions import CausalGraphErrors
22
23
  from cai_causal_graph.graph_components import Node
23
- from cai_causal_graph.type_definitions import NodeLike
24
+ from cai_causal_graph.type_definitions import EdgeType, NodeLike
24
25
 
25
26
 
26
27
  def _verify_identify_inputs(
@@ -387,3 +388,54 @@ def identify_markov_boundary(graph: Union[CausalGraph, Skeleton], node: NodeLike
387
388
  mb = graph.get_neighbors(node_id)
388
389
 
389
390
  return mb
391
+
392
+
393
+ def identify_colliders(graph: CausalGraph, unshielded_only: bool = False) -> List[str]:
394
+ """
395
+ Identify all the collider nodes in the provided `graph`.
396
+
397
+ :param graph: The graph given by a `cai_causal_graph.causal_graph.CausalGraph` instance.
398
+ :param unshielded_only: If `True`, only unshielded colliders are returned. If `False`, all colliders are returned.
399
+ Default is `False`. A collider is unshielded if there is no edge between any of its parents.
400
+ :return: A list of all node identifiers for the collider nodes in the graph.
401
+ """
402
+ colliders = set()
403
+
404
+ bidirected_edges = [(edge.source.identifier, edge.destination.identifier) for edge in graph.get_bidirected_edges()]
405
+
406
+ # go through every node in the graph
407
+ for node in graph.get_node_names():
408
+ # the node z is collider if x <> z <> y, x -> z <- y, x <> z <- y, or x -> z <> y
409
+ neighbors = graph.get_neighbors(node)
410
+
411
+ potential_parents = set()
412
+
413
+ for neighbor_node in neighbors:
414
+ # we need to check if the directed edge (neigh_node, node) exists
415
+ directed_exists = (
416
+ graph.edge_exists(neighbor_node, node)
417
+ and graph.get_edge(neighbor_node, node).edge_type == EdgeType.DIRECTED_EDGE
418
+ )
419
+ # we need to check if the bi-directed edge (neigh_node, node) or (node, neigh_node) exists
420
+ bidirected_exists = (neighbor_node, node) in bidirected_edges or (node, neighbor_node) in bidirected_edges
421
+
422
+ condition = directed_exists or bidirected_exists
423
+
424
+ if condition:
425
+ potential_parents.add(neighbor_node)
426
+
427
+ if len(potential_parents) >= 2:
428
+ # check if the collider is unshielded. A collider is unshielded if there is no edge between any of its
429
+ # parents
430
+ is_unshielded = True
431
+ if unshielded_only:
432
+ # test all the possible combinations of the potential parents
433
+ for parent_1, parent_2 in combinations(potential_parents, 2):
434
+ if graph.edge_exists(parent_1, parent_2) or graph.edge_exists(parent_2, parent_1):
435
+ is_unshielded = False
436
+ break
437
+
438
+ if not unshielded_only or is_unshielded:
439
+ colliders.add(node)
440
+
441
+ return list(colliders)
@@ -17,6 +17,7 @@ limitations under the License.
17
17
  from __future__ import annotations
18
18
 
19
19
  import logging
20
+ from collections import defaultdict
20
21
  from copy import deepcopy
21
22
  from functools import wraps
22
23
  from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
@@ -68,6 +69,8 @@ class TimeSeriesCausalGraph(CausalGraph):
68
69
  _NodeCls: Type[TimeSeriesNode] = TimeSeriesNode
69
70
  _EdgeCls: Type[Edge] = Edge
70
71
  _SummaryGraphCls: Type[CausalGraph] = CausalGraph
72
+ _lag_to_nodes: Dict[int, List[TimeSeriesNode]]
73
+ _variable_name_to_nodes: Dict[str, List[TimeSeriesNode]]
71
74
 
72
75
  def __init__(
73
76
  self,
@@ -111,6 +114,9 @@ class TimeSeriesCausalGraph(CausalGraph):
111
114
  be created. If either or both are provided, but this is `False` (default), then the nodes will be added but
112
115
  not connected by edges.
113
116
  """
117
+ # Initialize caches for fast lookups
118
+ self._lag_to_nodes = defaultdict(list)
119
+ self._variable_name_to_nodes = defaultdict(list)
114
120
  super().__init__(input_list, output_list, fully_connected)
115
121
 
116
122
  # list of variables in the graph, i.e. discarding the lags (X1(t-1) and X1 are the same variable)
@@ -203,11 +209,12 @@ class TimeSeriesCausalGraph(CausalGraph):
203
209
 
204
210
  # now extend the minimal graph to the current max and min lag to match the current graph
205
211
  self._stationary_graph = minimal_graph.extend_graph(-neg_lag, pos_lag)
212
+
206
213
  return self._stationary_graph
207
214
 
208
215
  def get_minimal_graph(self) -> TimeSeriesCausalGraph:
209
216
  """
210
- Return a minimal graph.
217
+ Return a minimal time series causal graph.
211
218
 
212
219
  The minimal graph is the graph with the minimal number of edges that is equivalent to the original graph.
213
220
  In other words, it is a graph that has no edges whose destination is not time delta 0.
@@ -444,7 +451,10 @@ class TimeSeriesCausalGraph(CausalGraph):
444
451
  return self._summary_graph
445
452
 
446
453
  def extend_graph(
447
- self, backward_steps: Optional[int] = None, forward_steps: Optional[int] = None
454
+ self,
455
+ backward_steps: Optional[int] = None,
456
+ forward_steps: Optional[int] = None,
457
+ include_all_parents: bool = False,
448
458
  ) -> TimeSeriesCausalGraph:
449
459
  """
450
460
  Return an extended graph.
@@ -460,6 +470,12 @@ class TimeSeriesCausalGraph(CausalGraph):
460
470
 
461
471
  :param backward_steps: Number of steps to extend the graph backwards in time. If None, do not extend backwards.
462
472
  :param forward_steps: Number of steps to extend the graph forwards in time. If None, do not extend forwards.
473
+ :param include_all_parents: If `True`, any nodes and edges required to predict nodes up to `backward_steps` ago
474
+ will also be added, in addition to the nodes/edges normally added by this method. This may mean that nodes
475
+ further back in time than `backward_steps` will be added, if they are parents of any nodes up to
476
+ `backward_steps` ago. Default is `False`, meaning this extra nodes/edges are not added.
477
+ `include_all_parents` is only valid when specifying a `backward_steps`, and will have no effect on the
478
+ logic of `forward_steps`.
463
479
  :return: Extended graph with nodes for each variable at each time step from `backward_steps` to `forward_steps`.
464
480
  """
465
481
  # check steps are valid (positive integers) if not None
@@ -504,8 +520,9 @@ class TimeSeriesCausalGraph(CausalGraph):
504
520
 
505
521
  lagged_destination_node = self._get_lagged_node(node=edge.destination, lag=-lag)
506
522
 
507
- # check if the new source node would go beyond the backward_steps
508
- if -lag - time_delta < -backward_steps:
523
+ # check if the new source node would go beyond the backward_steps, and do not add if
524
+ # include_all_parents is False
525
+ if (-lag - time_delta < -backward_steps) and not include_all_parents:
509
526
  continue
510
527
 
511
528
  lagged_source_node = self._get_lagged_node(node=edge.source, lag=-lag - time_delta)
@@ -711,6 +728,7 @@ class TimeSeriesCausalGraph(CausalGraph):
711
728
 
712
729
  identifier = self._check_node_exists(node)
713
730
  self._nodes_by_identifier[identifier] = node
731
+ self._add_node_to_cache(node)
714
732
 
715
733
  return node
716
734
 
@@ -758,6 +776,9 @@ class TimeSeriesCausalGraph(CausalGraph):
758
776
 
759
777
  See `cai_causal_graph.causal_graph.CausalGraph.delete_node` for more details.
760
778
  """
779
+ node = self.get_node(self._NodeCls.identifier_from(identifier))
780
+ assert isinstance(node, TimeSeriesNode) # for linting
781
+ self._remove_node_from_cache(node)
761
782
  super().delete_node(identifier)
762
783
 
763
784
  @_reset_ts_graph_attributes
@@ -1014,16 +1035,18 @@ class TimeSeriesCausalGraph(CausalGraph):
1014
1035
  cls,
1015
1036
  adjacency_matrices: Dict[int, numpy.ndarray],
1016
1037
  variable_names: Optional[List[Union[NodeLike, int]]] = None,
1038
+ construct_minimal: bool = True,
1017
1039
  ) -> TimeSeriesCausalGraph:
1018
1040
  """
1019
- Return a time series causal graph from a dictionary of adjacency matrices. Keys are the time deltas.
1020
- This is useful for converting a list of adjacency matrices into a time series causal graph.
1041
+ Instantiate a `cai_causal_graph.time_series_causal_graph.TimeSeriesCausalGraph` from a dictionary of
1042
+ adjacency matrices.
1043
+
1044
+ Keys are the time deltas. This is useful for converting a list of adjacency matrices into a
1045
+ `cai_causal_graph.time_series_causal_graph.TimeSeriesCausalGraph`.
1021
1046
 
1022
1047
  For example, the adjacency matrix with time delta -1 is stored in adjacency_matrices[-1] and would correspond
1023
1048
  to X-1 -> X, where X is the set of nodes.
1024
1049
 
1025
- Moreover, if floating nodes are present, only the contemporaneous nodes will be added to the graph.
1026
-
1027
1050
  Example:
1028
1051
  >>> import numpy
1029
1052
  >>> from cai_causal_graph import TimeSeriesCausalGraph
@@ -1054,6 +1077,7 @@ class TimeSeriesCausalGraph(CausalGraph):
1054
1077
  :param adjacency_matrices: A dictionary of adjacency matrices. Keys are the time delta.
1055
1078
  :param variable_names: A list of variable names. If not provided, the variable names are integers starting
1056
1079
  from 0. Node names must correspond to the variable names and must not contain the lag.
1080
+ :param construct_minimal: Whether to return a minimal time series graph. Default is `True`.
1057
1081
  :return: A time series causal graph.
1058
1082
  """
1059
1083
  assert isinstance(adjacency_matrices, dict)
@@ -1116,20 +1140,26 @@ class TimeSeriesCausalGraph(CausalGraph):
1116
1140
  time_delta_to_index[0] + (n_time_delta * column),
1117
1141
  ] = 1
1118
1142
 
1119
- return cls.from_adjacency_matrix(adjacency_matrix_full, node_names) # type: ignore
1143
+ graph = cls.from_adjacency_matrix(adjacency_matrix_full, node_names) # type: ignore
1144
+
1145
+ if construct_minimal:
1146
+ graph = graph.get_minimal_graph()
1147
+
1148
+ return graph
1120
1149
 
1121
1150
  @property
1122
1151
  def adjacency_matrices(self) -> Dict[int, numpy.ndarray]:
1123
1152
  """
1124
- Return the adjacency matrix dictionary of the minimal causal graph.
1153
+ Return the adjacency matrix dictionary of the minimal time series causal graph.
1125
1154
 
1126
1155
  The keys are the time deltas and the values are the adjacency matrices.
1127
1156
  """
1128
1157
  adjacency_matrices: Dict[int, numpy.ndarray] = {}
1158
+
1129
1159
  # get the minimal graph
1130
1160
  graph = self.get_minimal_graph()
1131
1161
 
1132
- if self.variables is None:
1162
+ if graph.variables is None:
1133
1163
  return adjacency_matrices
1134
1164
 
1135
1165
  for edge in graph.edges:
@@ -1140,7 +1170,7 @@ class TimeSeriesCausalGraph(CausalGraph):
1140
1170
  edge.source.meta[TIME_LAG],
1141
1171
  )
1142
1172
  if source_lag not in adjacency_matrices:
1143
- adjacency_matrices[source_lag] = numpy.zeros((len(self.variables), len(self.variables)))
1173
+ adjacency_matrices[source_lag] = numpy.zeros((len(graph.variables), len(graph.variables)))
1144
1174
 
1145
1175
  destination_variable_name, _ = (
1146
1176
  edge.destination.meta[VARIABLE_NAME],
@@ -1149,14 +1179,14 @@ class TimeSeriesCausalGraph(CausalGraph):
1149
1179
 
1150
1180
  if edge.get_edge_type() == EdgeType.DIRECTED_EDGE:
1151
1181
  adjacency_matrices[source_lag][
1152
- self.variables.index(source_variable_name), self.variables.index(destination_variable_name)
1182
+ graph.variables.index(source_variable_name), graph.variables.index(destination_variable_name)
1153
1183
  ] = 1
1154
1184
  elif edge.get_edge_type() == EdgeType.UNDIRECTED_EDGE:
1155
1185
  adjacency_matrices[source_lag][
1156
- self.variables.index(source_variable_name), self.variables.index(destination_variable_name)
1186
+ graph.variables.index(source_variable_name), graph.variables.index(destination_variable_name)
1157
1187
  ] = 1
1158
1188
  adjacency_matrices[source_lag][
1159
- self.variables.index(destination_variable_name), self.variables.index(source_variable_name)
1189
+ graph.variables.index(destination_variable_name), graph.variables.index(source_variable_name)
1160
1190
  ] = 1
1161
1191
  else:
1162
1192
  raise TypeError(
@@ -1243,7 +1273,7 @@ class TimeSeriesCausalGraph(CausalGraph):
1243
1273
 
1244
1274
  def to_numpy_by_lag(self) -> Tuple[Dict[int, numpy.ndarray], List[str]]:
1245
1275
  """
1246
- Return the adjacency matrices of the time series causal graph ordered by the time delta.
1276
+ Return the adjacency matrices of the minimal time series causal graph ordered by the time delta.
1247
1277
 
1248
1278
  Different time deltas are represented by different adjacency matrices.
1249
1279
  The keys of the dictionary are the time deltas and the values are the adjacency matrices.
@@ -1253,8 +1283,38 @@ class TimeSeriesCausalGraph(CausalGraph):
1253
1283
  # get the adjacency matrix
1254
1284
  adjacency_matrices = self.adjacency_matrices
1255
1285
 
1256
- assert self.variables is not None
1257
- return adjacency_matrices, self.variables
1286
+ # Adjacency matrices
1287
+ graph = self.get_minimal_graph()
1288
+
1289
+ assert graph.variables is not None
1290
+ return adjacency_matrices, graph.variables
1291
+
1292
+ def _add_node_to_cache(self, node: TimeSeriesNode):
1293
+ """Add a node to node caches."""
1294
+ self._lag_to_nodes[node.time_lag].append(node)
1295
+ self._variable_name_to_nodes[node.variable_name].append(node)
1296
+
1297
+ def _remove_node_from_cache(self, node: TimeSeriesNode):
1298
+ """Remove a node to node caches."""
1299
+ try:
1300
+ self._lag_to_nodes[node.time_lag].remove(node)
1301
+ if not self._lag_to_nodes[node.time_lag]:
1302
+ del self._lag_to_nodes[node.time_lag]
1303
+ except ValueError as e:
1304
+ raise ValueError(
1305
+ f'Tried to remove node {node.identifier} from `TimeSeriesCausalGraph._lag_to_nodes` cache but the '
1306
+ f'node was not found!'
1307
+ ) from e
1308
+
1309
+ try:
1310
+ self._variable_name_to_nodes[node.variable_name].remove(node)
1311
+ if not self._variable_name_to_nodes[node.variable_name]:
1312
+ del self._variable_name_to_nodes[node.variable_name]
1313
+ except ValueError as e:
1314
+ raise ValueError(
1315
+ f'Tried to remove node {node.identifier} from `TimeSeriesCausalGraph.variable_name_to_nodes` cache '
1316
+ f'but the node was not found!'
1317
+ ) from e
1258
1318
 
1259
1319
  def get_nodes_at_lag(self, time_lag: int = 0) -> List[TimeSeriesNode]:
1260
1320
  """
@@ -1262,8 +1322,7 @@ class TimeSeriesCausalGraph(CausalGraph):
1262
1322
 
1263
1323
  :param time_lag: Time lag to return nodes for. Default is `0`.
1264
1324
  """
1265
- # TODO Efficiency: don't loop through all nodes, by caching a lag -> node mapping: CAUSALAI-4384
1266
- return [node for node in self.get_nodes() if node.time_lag == time_lag]
1325
+ return self._lag_to_nodes[time_lag]
1267
1326
 
1268
1327
  def get_nodes_for_variable_name(self, variable_name: str) -> List[TimeSeriesNode]:
1269
1328
  """
@@ -1271,8 +1330,7 @@ class TimeSeriesCausalGraph(CausalGraph):
1271
1330
 
1272
1331
  :param variable_name: Variable name to return nodes for.
1273
1332
  """
1274
- # TODO Efficiency: don't loop through all nodes, by caching a variable -> node mapping: CAUSALAI-4384
1275
- return [node for node in self.get_nodes() if node.variable_name == variable_name]
1333
+ return self._variable_name_to_nodes[variable_name]
1276
1334
 
1277
1335
  def get_contemporaneous_nodes(self, node: NodeLike) -> List[TimeSeriesNode]:
1278
1336
  """Return all nodes that are contemporaneous (i.e. have the same time_lag) to the provided node."""
@@ -42,7 +42,7 @@ cache_dir = '/dev/null'
42
42
 
43
43
  [tool.poetry]
44
44
  name = "cai-causal-graph"
45
- version = "0.4.6.dev0"
45
+ version = "0.4.7"
46
46
  description = "A Causal AI package for causal graphs."
47
47
  license = "Apache-2.0"
48
48
  authors = ["causaLens <opensource@causalens.com>"]
@@ -54,7 +54,12 @@ packages = [{include = "cai_causal_graph"}]
54
54
 
55
55
  [tool.poetry.dependencies]
56
56
  mypy-extensions = "^1.0.0"
57
- networkx = ">=3.0.0, <4.0.0"
57
+ # networkx 3.3 broke how get_all_simple_paths works so want to bound for now.
58
+ # networkx 3.1 is the last one to support 3.8. We will drop 3.8 on next minor.
59
+ networkx = [
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
+ ]
58
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.
59
64
  # 1.26 is the first version to support 3.12, but want to allow other versions to support earlier numpy.
60
65
  numpy = [