|
| 1 | +"""Module containing classes to define and run causal surrogate assisted test cases""" |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Callable |
| 6 | + |
| 7 | +from causal_testing.data_collection.data_collector import ObservationalDataCollector |
| 8 | +from causal_testing.specification.causal_specification import CausalSpecification |
| 9 | +from causal_testing.testing.base_test_case import BaseTestCase |
| 10 | +from causal_testing.testing.estimators import CubicSplineRegressionEstimator |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class SimulationResult: |
| 15 | + """Data class holding the data and result metadata of a simulation""" |
| 16 | + |
| 17 | + data: dict |
| 18 | + fault: bool |
| 19 | + relationship: str |
| 20 | + |
| 21 | + |
| 22 | +class SearchAlgorithm(ABC): # pylint: disable=too-few-public-methods |
| 23 | + """Class to be inherited with the search algorithm consisting of a search function and the fitness function of the |
| 24 | + space to be searched""" |
| 25 | + |
| 26 | + @abstractmethod |
| 27 | + def search( |
| 28 | + self, surrogate_models: list[CubicSplineRegressionEstimator], specification: CausalSpecification |
| 29 | + ) -> list: |
| 30 | + """Function which implements a search routine which searches for the optimal fitness value for the specified |
| 31 | + scenario |
| 32 | + :param surrogate_models: The surrogate models to be searched |
| 33 | + :param specification: The Causal Specification (combination of Scenario and Causal Dag)""" |
| 34 | + |
| 35 | + |
| 36 | +class Simulator(ABC): |
| 37 | + """Class to be inherited with Simulator specific functions to start, shutdown and run the simulation with the give |
| 38 | + config file""" |
| 39 | + |
| 40 | + @abstractmethod |
| 41 | + def startup(self, **kwargs): |
| 42 | + """Function that when run, initialises and opens the Simulator""" |
| 43 | + |
| 44 | + @abstractmethod |
| 45 | + def shutdown(self, **kwargs): |
| 46 | + """Function to safely exit and shutdown the Simulator""" |
| 47 | + |
| 48 | + @abstractmethod |
| 49 | + def run_with_config(self, configuration: dict) -> SimulationResult: |
| 50 | + """Run the simulator with the given configuration and return the results in the structure of a |
| 51 | + SimulationResult |
| 52 | + :param configuration: The configuration required to initialise the Simulation |
| 53 | + :return: Simulation results in the structure of the SimulationResult data class""" |
| 54 | + |
| 55 | + |
| 56 | +class CausalSurrogateAssistedTestCase: |
| 57 | + """A class representing a single causal surrogate assisted test case.""" |
| 58 | + |
| 59 | + def __init__( |
| 60 | + self, |
| 61 | + specification: CausalSpecification, |
| 62 | + search_algorithm: SearchAlgorithm, |
| 63 | + simulator: Simulator, |
| 64 | + ): |
| 65 | + self.specification = specification |
| 66 | + self.search_algorithm = search_algorithm |
| 67 | + self.simulator = simulator |
| 68 | + |
| 69 | + def execute( |
| 70 | + self, |
| 71 | + data_collector: ObservationalDataCollector, |
| 72 | + max_executions: int = 200, |
| 73 | + custom_data_aggregator: Callable[[dict, dict], dict] = None, |
| 74 | + ): |
| 75 | + """For this specific test case, a search algorithm is used to find the most contradictory point in the input |
| 76 | + space which is, therefore, most likely to indicate incorrect behaviour. This cadidate test case is run against |
| 77 | + the simulator, checked for faults and the result returned with collected data |
| 78 | + :param data_collector: An ObservationalDataCollector which gathers data relevant to the specified scenario |
| 79 | + :param max_executions: Maximum number of simulator executions before exiting the search |
| 80 | + :param custom_data_aggregator: |
| 81 | + :return: tuple containing SimulationResult or str, execution number and collected data""" |
| 82 | + data_collector.collect_data() |
| 83 | + |
| 84 | + for i in range(max_executions): |
| 85 | + surrogate_models = self.generate_surrogates(self.specification, data_collector) |
| 86 | + candidate_test_case, _, surrogate = self.search_algorithm.search(surrogate_models, self.specification) |
| 87 | + |
| 88 | + self.simulator.startup() |
| 89 | + test_result = self.simulator.run_with_config(candidate_test_case) |
| 90 | + self.simulator.shutdown() |
| 91 | + |
| 92 | + if custom_data_aggregator is not None: |
| 93 | + if data_collector.data is not None: |
| 94 | + data_collector.data = custom_data_aggregator(data_collector.data, test_result.data) |
| 95 | + else: |
| 96 | + data_collector.data = data_collector.data.append(test_result.data, ignore_index=True) |
| 97 | + |
| 98 | + if test_result.fault: |
| 99 | + print( |
| 100 | + f"Fault found between {surrogate.treatment} causing {surrogate.outcome}. Contradiction with " |
| 101 | + f"expected {surrogate.expected_relationship}." |
| 102 | + ) |
| 103 | + test_result.relationship = ( |
| 104 | + f"{surrogate.treatment} -> {surrogate.outcome} expected {surrogate.expected_relationship}" |
| 105 | + ) |
| 106 | + return test_result, i + 1, data_collector.data |
| 107 | + |
| 108 | + print("No fault found") |
| 109 | + return "No fault found", i + 1, data_collector.data |
| 110 | + |
| 111 | + def generate_surrogates( |
| 112 | + self, specification: CausalSpecification, data_collector: ObservationalDataCollector |
| 113 | + ) -> list[CubicSplineRegressionEstimator]: |
| 114 | + """Generate a surrogate model for each edge of the dag that specifies it is included in the DAG metadata. |
| 115 | + :param specification: The Causal Specification (combination of Scenario and Causal Dag) |
| 116 | + :param data_collector: An ObservationalDataCollector which gathers data relevant to the specified scenario |
| 117 | + :return: A list of surrogate models |
| 118 | + """ |
| 119 | + surrogate_models = [] |
| 120 | + |
| 121 | + for u, v in specification.causal_dag.graph.edges: |
| 122 | + edge_metadata = specification.causal_dag.graph.adj[u][v] |
| 123 | + if "included" in edge_metadata: |
| 124 | + from_var = specification.scenario.variables.get(u) |
| 125 | + to_var = specification.scenario.variables.get(v) |
| 126 | + base_test_case = BaseTestCase(from_var, to_var) |
| 127 | + |
| 128 | + minimal_adjustment_set = specification.causal_dag.identification(base_test_case, specification.scenario) |
| 129 | + |
| 130 | + surrogate = CubicSplineRegressionEstimator( |
| 131 | + u, |
| 132 | + 0, |
| 133 | + 0, |
| 134 | + minimal_adjustment_set, |
| 135 | + v, |
| 136 | + 4, |
| 137 | + df=data_collector.data, |
| 138 | + expected_relationship=edge_metadata["expected"], |
| 139 | + ) |
| 140 | + surrogate_models.append(surrogate) |
| 141 | + |
| 142 | + return surrogate_models |
0 commit comments