cai-causal-graph 0.4.0.dev3__tar.gz → 0.4.2.dev0__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.

Potentially problematic release.


This version of cai-causal-graph might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cai-causal-graph
3
- Version: 0.4.0.dev3
3
+ Version: 0.4.2.dev0
4
4
  Summary: A Causal AI package for causal graphs.
5
5
  Home-page: https://causalgraph.causalens.com/
6
6
  License: Apache-2.0
@@ -41,7 +41,7 @@ Documentation, including a quickstart and code reference docs, can be found [her
41
41
  ![INTERROGATE](https://github.com/causalens/cai-causal-graph/blob/main/interrogate_badge.svg?raw=true)
42
42
 
43
43
  > **Note**
44
- > The current development cycle of this branch is `v0.4.x` (development).
44
+ > The current development cycle of this branch is `v0.4.x` (stable).
45
45
 
46
46
  ## License
47
47
 
@@ -19,7 +19,7 @@ Documentation, including a quickstart and code reference docs, can be found [her
19
19
  ![INTERROGATE](https://github.com/causalens/cai-causal-graph/blob/main/interrogate_badge.svg?raw=true)
20
20
 
21
21
  > **Note**
22
- > The current development cycle of this branch is `v0.4.x` (development).
22
+ > The current development cycle of this branch is `v0.4.x` (stable).
23
23
 
24
24
  ## License
25
25
 
@@ -31,7 +31,7 @@ __all__ = [
31
31
  'VARIABLE_NAME',
32
32
  ]
33
33
 
34
- __version__ = '0.4.0.dev3'
34
+ __version__ = '0.4.2.dev0'
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
@@ -424,6 +424,11 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
424
424
  if not isinstance(item, tuple):
425
425
  return self.get_node(item)
426
426
  else:
427
+ if len(item) != 2:
428
+ raise TypeError(
429
+ f'The provided item must either be `NodeLike` (i.e. to return a single node) or a tuple of two '
430
+ f'`NodeLike` objects (i.e. to return an edge), got {item}.'
431
+ )
427
432
  return self.get_edge(item[0], item[1])
428
433
 
429
434
  def __iter__(self) -> Iterator:
@@ -627,7 +632,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
627
632
  )
628
633
  return source_nodes[0], destination_nodes[0]
629
634
 
630
- def _set_edge(self, source: NodeLike, destination: NodeLike, edge: Edge):
635
+ def _set_edge(self, source: NodeLike, destination: NodeLike, edge: Edge, validate: bool = True):
631
636
  """Set the edge in the graph."""
632
637
  if isinstance(source, HasIdentifier):
633
638
  source = source.identifier
@@ -642,13 +647,14 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
642
647
  self._nodes_by_identifier[source]._add_outbound_edge(edge)
643
648
 
644
649
  # check that there are no cycles of directed edges
645
- try:
646
- self._assert_node_does_not_depend_on_itself(destination)
647
- except AssertionError:
648
- self.delete_edge(source, destination)
649
- raise CausalGraphErrors.CyclicConnectionError(
650
- f'Adding an edge from {source} to {destination} would create a cyclic connection.'
651
- )
650
+ if validate:
651
+ try:
652
+ self._assert_node_does_not_depend_on_itself(destination)
653
+ except AssertionError:
654
+ self.delete_edge(source, destination)
655
+ raise CausalGraphErrors.CyclicConnectionError(
656
+ f'Adding an edge from {source} to {destination} would create a cyclic connection.'
657
+ )
652
658
 
653
659
  def _is_fully_directed(self) -> bool:
654
660
  """
@@ -1090,6 +1096,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1090
1096
  edge_type: EdgeType = EdgeType.DIRECTED_EDGE,
1091
1097
  meta: Optional[dict] = None,
1092
1098
  edge: Optional[Edge] = None,
1099
+ validate: bool = True,
1093
1100
  ) -> Edge:
1094
1101
  """
1095
1102
  Add an edge from a source to a destination node with a specific edge type.
@@ -1111,6 +1118,8 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1111
1118
  :param edge: A `cai_causal_graph.graph_components.Edge` edge to be used to construct a new edge. All the
1112
1119
  properties of the provided edge will be deep copied to the constructed edge, including metadata. If
1113
1120
  provided, then all other parameters to the method must not be specified. Default is `None`.
1121
+ :param validate: Whether to perform validation checks. The validation checks will raise if
1122
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
1114
1123
  :return: The created edge object.
1115
1124
  """
1116
1125
  if edge is not None:
@@ -1135,10 +1144,10 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1135
1144
  if meta is not None:
1136
1145
  edge.meta = meta
1137
1146
 
1138
- self._set_edge(source, destination, edge)
1147
+ self._set_edge(source, destination, edge, validate=validate)
1139
1148
  return edge
1140
1149
 
1141
- def add_edges_from(self, pairs: List[Tuple[NodeLike, NodeLike]]):
1150
+ def add_edges_from(self, pairs: List[Tuple[NodeLike, NodeLike]], validate: bool = True):
1142
1151
  """
1143
1152
  A convenience method to add multiple edges by specifying tuples of source and destination node identifiers.
1144
1153
 
@@ -1146,12 +1155,14 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1146
1155
  `cai_causal_graph.causal_graph.CausalGraph.add_edge` method.
1147
1156
 
1148
1157
  :param pairs: List of valid edge pairs, defined as tuples of `(source_identifier, destination_identifier)`.
1158
+ :param validate: Whether to perform validation checks. The validation checks will raise if
1159
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
1149
1160
  """
1150
1161
  for pair in pairs:
1151
1162
  validate_pair_type(pair)
1152
- self.add_edge(source=pair[0], destination=pair[1])
1163
+ self.add_edge(source=pair[0], destination=pair[1], validate=validate)
1153
1164
 
1154
- def add_edges_from_paths(self, paths: Union[List[NodeLike], List[List[NodeLike]]]):
1165
+ def add_edges_from_paths(self, paths: Union[List[NodeLike], List[List[NodeLike]]], validate: bool = True):
1155
1166
  """
1156
1167
  A convenience method to add multiple edges by specifying a single or a list of paths.
1157
1168
 
@@ -1168,6 +1179,8 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1168
1179
 
1169
1180
  :param paths: A list of paths or a single path. A path is defined as a list of node identifiers, defining the
1170
1181
  causal path in a causal graph.
1182
+ :param validate: Whether to perform validation checks. The validation checks will raise if
1183
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
1171
1184
  """
1172
1185
  assert len(paths) != 0, 'The `paths` parameter must not be an empty list.'
1173
1186
  if isinstance(paths[0], list):
@@ -1182,14 +1195,26 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1182
1195
  source, destination = cast(NodeLike, source), cast(NodeLike, destination)
1183
1196
  if not self.edge_exists(source=source, destination=destination):
1184
1197
  validate_pair_type((source, destination))
1185
- self.add_edge(source=source, destination=destination)
1198
+ self.add_edge(source=source, destination=destination, validate=validate)
1186
1199
 
1187
1200
  def add_edge_by_pair(
1188
- self, pair: Tuple[NodeLike, NodeLike], edge_type: EdgeType = EdgeType.DIRECTED_EDGE, meta: Optional[dict] = None
1201
+ self,
1202
+ pair: Tuple[NodeLike, NodeLike],
1203
+ edge_type: EdgeType = EdgeType.DIRECTED_EDGE,
1204
+ meta: Optional[dict] = None,
1205
+ validate: bool = True,
1189
1206
  ):
1190
- """Add edge by pair identifier (source, destination)."""
1207
+ """
1208
+ Add edge by pair identifier (source, destination).
1209
+
1210
+ :param pair: Tuple to identify the source and destination of the edge.
1211
+ :param edge_type: The type of edge to add. Default is a directed edge
1212
+ :param meta: Any metadata to add to the edge. Default is `None` (no metadata).
1213
+ :param validate: Whether to perform validation checks. The validation checks will raise if
1214
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
1215
+ """
1191
1216
  validate_pair_type(pair)
1192
- self.add_edge(pair[0], pair[1], edge_type=edge_type, meta=meta)
1217
+ self.add_edge(pair[0], pair[1], edge_type=edge_type, meta=meta, validate=validate)
1193
1218
 
1194
1219
  def remove_edge_by_pair(self, pair: Tuple[NodeLike, NodeLike], edge_type: Optional[EdgeType] = None):
1195
1220
  """Remove edge by pair identifier (source, destination)."""
@@ -1206,6 +1231,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1206
1231
  :param destination: Identifier of the node at which the edge terminates.
1207
1232
  :param edge_type: The edge type of the edge to be deleted. Default is None, in which case the type is ignored.
1208
1233
  """
1234
+ source, destination = Node.identifier_from(source), Node.identifier_from(destination)
1209
1235
  assert isinstance(source, str), 'Source identifier must be a string'
1210
1236
  assert isinstance(destination, str), 'Destination identifier must be a string'
1211
1237
 
@@ -1237,7 +1263,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1237
1263
  self._clean_empty_edge_dictionaries()
1238
1264
  edge.invalidate()
1239
1265
 
1240
- def remove_edge(self, /, source: str, destination: str, *, edge_type: Optional[EdgeType] = None):
1266
+ def remove_edge(self, /, source: NodeLike, destination: NodeLike, *, edge_type: Optional[EdgeType] = None):
1241
1267
  """Remove a specific edge by source and destination node identifiers, as well as edge type."""
1242
1268
  self.delete_edge(source=source, destination=destination, edge_type=edge_type)
1243
1269
 
@@ -1833,8 +1859,14 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1833
1859
  return '\n'.join(networkx.generate_gml(self.to_networkx()))
1834
1860
 
1835
1861
  @classmethod
1836
- def from_dict(cls, d: dict) -> CausalGraph:
1837
- """Construct a `cai_causal_graph.causal_graph.CausalGraph` instance from a Python dictionary."""
1862
+ def from_dict(cls, d: dict, validate: bool = True) -> CausalGraph:
1863
+ """
1864
+ Construct a `cai_causal_graph.causal_graph.CausalGraph` instance from a Python dictionary.
1865
+
1866
+ :param d: Dictionary to build a graph from.
1867
+ :param validate: Whether to perform validation checks. The validation checks will raise if
1868
+ any cycles are contained within the dictionary graph. Default is `True`.
1869
+ """
1838
1870
  graph = cls()
1839
1871
 
1840
1872
  for identifier, node_dict in d['nodes'].items():
@@ -1844,7 +1876,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1844
1876
  for source, destinations in d['edges'].items():
1845
1877
  for destination, edge_dict in destinations.items():
1846
1878
  edge = cls._EdgeCls.from_dict(edge_dict)
1847
- graph.add_edge(edge=edge)
1879
+ graph.add_edge(edge=edge, validate=validate)
1848
1880
 
1849
1881
  return graph
1850
1882
 
@@ -1878,9 +1910,9 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1878
1910
  g = networkx.parse_gml(gml)
1879
1911
  return CausalGraph.from_networkx(g)
1880
1912
 
1881
- @staticmethod
1913
+ @classmethod
1882
1914
  def from_adjacency_matrix(
1883
- adjacency: numpy.ndarray, node_names: Optional[List[Union[NodeLike, int]]] = None
1915
+ cls, adjacency: numpy.ndarray, node_names: Optional[List[Union[NodeLike, int]]] = None
1884
1916
  ) -> CausalGraph:
1885
1917
  """
1886
1918
  Construct a `cai_causal_graph.causal_graph.CausalGraph` instance from an adjacency matrix and optionally a list
@@ -1921,7 +1953,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1921
1953
  nodes = [CausalGraph.coerce_to_nodelike(node) for node in node_names] # type: ignore
1922
1954
 
1923
1955
  # Add edges. Any conversion from BasicFeature or BasicTarget is handled by the add_edge method.
1924
- graph = CausalGraph()
1956
+ graph = cls()
1925
1957
  graph.add_nodes_from(nodes)
1926
1958
  for i, j in itertools.combinations(range(len(nodes)), 2):
1927
1959
  if adjacency[i, j] != 0 and adjacency[j, i] == 0:
@@ -1941,7 +1973,7 @@ class CausalGraph(HasIdentifier, HasMetadata, CanDictSerialize, CanDictDeseriali
1941
1973
  :return: A copy of the `cai_causal_graph.causal_graph.CausalGraph` instance.
1942
1974
  """
1943
1975
  graph_dict = self.to_dict(include_meta=include_meta)
1944
- new_graph = self.__class__.from_dict(graph_dict)
1976
+ new_graph = self.__class__.from_dict(graph_dict, validate=False)
1945
1977
  assert isinstance(new_graph, self.__class__) # for linting and sanity check
1946
1978
  return new_graph
1947
1979
 
@@ -245,7 +245,8 @@ class TimeSeriesCausalGraph(CausalGraph):
245
245
 
246
246
  edge = self._EdgeCls(source=source, destination=destination, edge_type=edge.edge_type, meta=edge.meta)
247
247
 
248
- minimal_cg.add_edge(edge=edge)
248
+ # Do not check for acyclicity as we know the original graph was a DAG, so this will be a DAG
249
+ minimal_cg.add_edge(edge=edge, validate=False)
249
250
 
250
251
  # otherwise if the time delta is not 0, we may have X[t-2]->X[t-1] and
251
252
  # we must add X[t-1]->X[t]
@@ -275,8 +276,8 @@ class TimeSeriesCausalGraph(CausalGraph):
275
276
  edge = self._EdgeCls(
276
277
  source=source, destination=destination, edge_type=edge.edge_type, meta=edge.meta
277
278
  )
278
-
279
- minimal_cg.add_edge(edge=edge)
279
+ # Do not check for acyclicity as we know the original graph was a DAG, so this will be a DAG
280
+ minimal_cg.add_edge(edge=edge, validate=False)
280
281
 
281
282
  # check for floating nodes
282
283
  if self.variables is not None and len(self.variables) > 0:
@@ -504,6 +505,7 @@ class TimeSeriesCausalGraph(CausalGraph):
504
505
  destination=lagged_destination_node,
505
506
  edge_type=edge.get_edge_type(),
506
507
  meta=edge.meta,
508
+ validate=False,
507
509
  )
508
510
 
509
511
  # Log a warning if the backward_steps is smaller than the maximum lag in the graph.
@@ -554,6 +556,7 @@ class TimeSeriesCausalGraph(CausalGraph):
554
556
  destination=extended_graph.get_node(lagged_dest.identifier),
555
557
  edge_type=edge.get_edge_type(),
556
558
  meta=edge.meta,
559
+ validate=False,
557
560
  )
558
561
 
559
562
  return extended_graph
@@ -817,6 +820,7 @@ class TimeSeriesCausalGraph(CausalGraph):
817
820
  edge_type: EdgeType = EdgeType.DIRECTED_EDGE,
818
821
  meta: Optional[dict] = None,
819
822
  edge: Optional[Edge] = None,
823
+ validate: bool = True,
820
824
  ) -> Edge:
821
825
  """
822
826
  Add an edge from a source to a destination node with a specific edge type.
@@ -840,6 +844,8 @@ class TimeSeriesCausalGraph(CausalGraph):
840
844
  :param edge: A `cai_causal_graph.graph_components.Edge` edge to be used to construct a new edge. All the
841
845
  properties of the provided edge will be deep copied to the constructed edge, including metadata. If
842
846
  provided, then all other parameters to the method must not be specified. Default is `None`.
847
+ :param validate: Whether to perform validation checks. The validation checks will raise if
848
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
843
849
  :return: The created edge object.
844
850
  """
845
851
  if edge is not None:
@@ -890,7 +896,14 @@ class TimeSeriesCausalGraph(CausalGraph):
890
896
  source, destination = destination, source
891
897
 
892
898
  self._check_nodes_and_edge(source=source, destination=destination, edge_type=edge_type, edge=edge)
893
- edge = super().add_edge(source=source, destination=destination, edge_type=edge_type, meta=meta, edge=edge)
899
+ edge = super().add_edge(
900
+ source=source,
901
+ destination=destination,
902
+ edge_type=edge_type,
903
+ meta=meta,
904
+ edge=edge,
905
+ validate=validate,
906
+ )
894
907
 
895
908
  return edge
896
909
 
@@ -904,6 +917,7 @@ class TimeSeriesCausalGraph(CausalGraph):
904
917
  destination_time: int,
905
918
  *,
906
919
  meta: Optional[dict] = None,
920
+ validate: bool = True,
907
921
  ) -> Edge:
908
922
  """
909
923
  Add a time edge to the graph from the variable at the source time to the variable at the destination time.
@@ -913,6 +927,8 @@ class TimeSeriesCausalGraph(CausalGraph):
913
927
  :param destination_variable: The name of the destination variable.
914
928
  :param destination_time: The time of the destination variable.
915
929
  :param meta: The metadata for the edge.
930
+ :param validate: Whether to perform validation checks. The validation checks will raise if
931
+ any cycles are introduced to the graph by adding the edge. Default is `True`.
916
932
  :return: The edge that was added.
917
933
 
918
934
  Example:
@@ -928,7 +944,7 @@ class TimeSeriesCausalGraph(CausalGraph):
928
944
  source = get_name_with_lag(source_variable, source_time)
929
945
  destination = get_name_with_lag(destination_variable, destination_time)
930
946
 
931
- return self.add_edge(source, destination, meta=meta)
947
+ return self.add_edge(source, destination, meta=meta, validate=validate)
932
948
 
933
949
  @classmethod
934
950
  def from_causal_graph(cls, causal_graph: CausalGraph) -> TimeSeriesCausalGraph:
@@ -964,7 +980,7 @@ class TimeSeriesCausalGraph(CausalGraph):
964
980
  assert isinstance(source, TimeSeriesNode) # for linting
965
981
  assert isinstance(destination, TimeSeriesNode) # for linting
966
982
 
967
- ts_cg.add_edge(source, destination, meta=edge.meta, edge_type=edge.get_edge_type())
983
+ ts_cg.add_edge(source, destination, meta=edge.meta, edge_type=edge.get_edge_type(), validate=False)
968
984
 
969
985
  ts_cg._sepsets = sepsets
970
986
 
@@ -42,7 +42,7 @@ cache_dir = '/dev/null'
42
42
 
43
43
  [tool.poetry]
44
44
  name = "cai-causal-graph"
45
- version = "0.4.0.dev3"
45
+ version = "0.4.2.dev0"
46
46
  description = "A Causal AI package for causal graphs."
47
47
  license = "Apache-2.0"
48
48
  authors = ["causaLens <opensource@causalens.com>"]