Test Minimisation with CausalCut

In this tutorial, we will show how to apply causal testing to determine which interventions in a sequence were necessary to bring about a given failure.

Motivating Example

Consider a controller system for a slow release water tank. The system has an inlet pump, an outlet valve, and a sensor to measure the level. The tank initially starts empty, with the outlet valve is closed, and the inlet pump switched off. The controller then has the following dynamics:

  • If the tank level falls to 20% of its capacity, the inlet pump is switched on.

  • When the tank reaches 70% capacity, the pump is switched off.

  • If the tank ever reaches 90% capacity, the outlet valve is opened.

  • When the tank level falls to 30% capacity, the outlet valve is closed.

[1]:
import pandas as pd

class SimpleTank():
    def __init__(self, tank_size:int, tank_level: float = 0, pump_on: bool = False, valve_open:bool = False):
        self.time = 0
        self.tank_level = tank_level
        self.pump_on = pump_on
        self.valve_open = valve_open
        self.tank_size = tank_size

    def tick(self):
        # Time actions
        self.time += 1
        if self.tank_level > 0.1:
            if self.valve_open:
                self.tank_level -= 1
            else:
                # Slow release
                self.tank_level -= 0.1
        if self.pump_on:
            self.tank_level += 3

        # Set actuators based on sensor values
        if self.tank_level >= 0.7 * self.tank_size:
            self.pump_on = False
        if self.tank_level >= 0.9 * self.tank_size:
            self.valve_open = True
        if self.tank_level <= 0.3 * self.tank_size:
            self.valve_open = False
        if self.tank_level <= 0.2 * self.tank_size:
            self.pump_on = True


    def state(self):
        return {
            "time": self.time,
            "tank_level": self.tank_level,
            "pump_on": self.pump_on,
            "valve_open": self.valve_open,
            "tank_size": self.tank_size,
        }


def run_pump(time_steps:int):
    simple_tank = SimpleTank(tank_size=10)
    data = []
    for step in range(time_steps):
        data.append(simple_tank.state())
        simple_tank.tick()
    return pd.DataFrame(data)

run_pump(10)
[1]:
time tank_level pump_on valve_open tank_size
0 0 0.0 False False 10
1 1 0.0 True False 10
2 2 3.0 True False 10
3 3 5.9 True False 10
4 4 8.8 False False 10
5 5 8.7 False False 10
6 6 8.6 False False 10
7 7 8.5 False False 10
8 8 8.4 False False 10
9 9 8.3 False False 10

Unlike traditional software, this is a hybrid system that involves interaction between digital software and the real world via sensors and actuators. Sensors provide us with a continuous stream of values which change over time (the level of the tank). Actuators (in this case, the pump and the valve) can be turned on or off by the system in response to sensor readings. In turn, the state of the actuators then goes on to influence subsequent sensor readings.

This means that, unlike the standard Causal Testing workflow, where tests represent interventions on variables at a single point in time, tests are here specified as sequences of interventions of the form (time_step, variable, value). For example, we may force the pump to be on for the first four time steps in an attempt to cause the tank to overflow. This represents four separate interventions on the pump (one for each time step) since the system may autonomously turn the pump off if we do not force it to remain on. We can express this as follows:

[2]:
test_case = [(time_step, "pump_on", True) for time_step in range(1, 5)]
test_case
[2]:
[(1, 'pump_on', True),
 (2, 'pump_on', True),
 (3, 'pump_on', True),
 (4, 'pump_on', True)]

To execute this test case on the tank system, we can define a modified version of run_pump:

[3]:
def run_pump_test(time_steps:int, interventions:list[tuple[int, str, bool]], tank_size:int = 10):
    simple_tank = SimpleTank(tank_size=tank_size)
    data = []
    for step in range(time_steps):
        data.append(simple_tank.state())
        simple_tank.tick()
        # Apply the interventions for each time step
        for time, var, val in interventions:
            if time == step:
                setattr(simple_tank, var, val)
    return pd.DataFrame(data)

# Keep the pump on for the first 4 time steps
# The 0th time step here represents the initial state, which we cannot intervene on
run_pump_test(time_steps=10, interventions=test_case)
[3]:
time tank_level pump_on valve_open tank_size
0 0 0.0 False False 10
1 1 0.0 True False 10
2 2 3.0 True False 10
3 3 5.9 True False 10
4 4 8.8 True False 10
5 5 11.7 True True 10
6 6 13.7 False True 10
7 7 12.7 False True 10
8 8 11.7 False True 10
9 9 10.7 False True 10

Test Minimisation

We can see that the above test case causes the tank to overflow at time step five, since the tank level exceeds the tank size. However, we may not need all four pump_on interventions to achieve this. The question then is “Which interventions were actually necessary to cause the failure?” This is exactly the question that CausalCut is intended to answer.

A naive approach to this question would be to simply run every possible subset of interventions in order to find out which one brings about the failure.

[4]:
from itertools import chain, combinations

def powerset(iterable):
    """
    Subsequences of the iterable from shortest to longest.
    """
    # powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def find_minimal_test():
    """
    Try every subset of interventions from the test case from shortest to longest.
    """
    for interventions in powerset(test_case):
        df = run_pump_test(time_steps=10, interventions=interventions)
        if (df["tank_level"] > df["tank_size"]).any():
            return list(interventions)

find_minimal_test()
[4]:
[(3, 'pump_on', True)]

We see here that we only need a single intervention to force an overflow here. However, for more complex systems that take a long time to run, it may be prohibitive to check every combination. This is where the two-step minimisation approach of CausalCut comes in.

  • In the first phase, CausalCut uses previous runtime data to estimate the causal contribution of each intervention to the observed failure. Any intervention not estimated to have a significant contribution is pruned.

  • In the second phase, CausalCut iteritively re-adds the pruned interventions in order of their estimated causal contribution until the original failure is produced.

For a detailed explanation of the algorithm, we refer the users to the API documentation or this paper.

Causal Graph

As with all causal testing, we need to specify the causal relationships within the system. This is a little different from the rest of how the Causal Testing Framework operates because we have feedback between variables over time. Where the rest of the framework assumes an acyclic causal structure, this is exactly what we have here.

Causal structure of the simple tank system with feedback cycles

Data Collection

The first phase of CausalCut intolves using pre-existing data to estimate the causal contribution of each event to a failure. This involves inverting the value of each intervention individually and comparing the new “treatment strategy” to the original test.

[5]:
sequences_to_check = []
for i in range(len(test_case)):
    sequences_to_check.append([(time, variable, not value if index == i else value) for index, (time, variable, value) in enumerate(test_case)])
sequences_to_check
[5]:
[[(1, 'pump_on', False),
  (2, 'pump_on', True),
  (3, 'pump_on', True),
  (4, 'pump_on', True)],
 [(1, 'pump_on', True),
  (2, 'pump_on', False),
  (3, 'pump_on', True),
  (4, 'pump_on', True)],
 [(1, 'pump_on', True),
  (2, 'pump_on', True),
  (3, 'pump_on', False),
  (4, 'pump_on', True)],
 [(1, 'pump_on', True),
  (2, 'pump_on', True),
  (3, 'pump_on', True),
  (4, 'pump_on', False)]]

When collecting data, the two columns you must include are an id column to give a unique identifier to each run, and a time column to record sequential time steps within each run. You should then record the values of each sensor and the state of each actuator throughout the run. Data should be supplied in “long format”, that is, with runs concatenated together to share columns.

Ideally, we would have many repeated runs for both the original test case and each “treatment strategy”, with no other interventions. The fewer repeated runs that are observed, the less reliable the estimated effect will be, and the more likely it is that necessary interventions will be pruned by phase one. If we lack data entirely for a particular treatment strategy, we cannot estimate the causal effect of the corresponding intervention at all, because we have no data on which to base the estimate.

[6]:
import random
random.seed(1)
TIME_STEPS=10

def collect_data():
    """
    Collect some random runs of the simple tank system.
    """
    runs = []
    num_runs = 200
    for i in range(num_runs):
        runs.append(
            run_pump_test(time_steps=TIME_STEPS, interventions=[(time, "pump_on", random.choice([True, False])) for time in random.sample(range(10), random.randint(0, TIME_STEPS))], tank_size=random.randint(8, 12)).assign(id=i)
        )
    return pd.concat(runs)
df = collect_data()
df
[6]:
time tank_level pump_on valve_open tank_size id
0 0 0.0 False False 11 0
1 1 0.0 True False 11 0
2 2 3.0 True False 11 0
3 3 5.9 True False 11 0
4 4 8.8 False False 11 0
... ... ... ... ... ... ...
5 5 8.7 False False 12 199
6 6 8.6 False False 12 199
7 7 8.5 False False 12 199
8 8 8.4 False False 12 199
9 9 8.3 False False 12 199

2000 rows × 6 columns

System Interaction

The second phase of CausalCut involves running the system to see if the pruned sequence of interventions still yields the original failure. To do this, you must provide a python function that takes a sequence of interventions, runs your system with those interventions, and returns True if the failure is observed and False otherwise.

[7]:
def reproduce_overflow_fault(interventions: list[tuple[int, str, bool]]):
    simple_tank = SimpleTank(tank_size=10)
    for step in range(TIME_STEPS):
        # Check overflow
        if simple_tank.tank_level > simple_tank.tank_size:
            return True
        simple_tank.tick()
        # Apply the interventions for each time step
        for time, var, val in interventions:
            if time == step:
                setattr(simple_tank, var, val)
    return False

Test Minimisation

Having collected data and defined the system interaction function, test minimisation is as simple as instantiating the CausalCut class and running minimise_test with the appropriate arguments.

[8]:
from causal_testing.minimisation.causal_cut import CausalCut
from causal_testing.specification.causal_dag import CausalDAG

causal_cut = CausalCut(
        dag=CausalDAG("dcg.dot", ignore_cycles=True),
        df=df,
        safe_ranges=pd.DataFrame({"tank_level": {"low": 0, "high": 10}}).T,
        reproduce_fault=reproduce_overflow_fault
    )
minimised_test = causal_cut.minimise_test(
    interventions=test_case,
    outcome_variable="tank_level",
    total_time=TIME_STEPS,
    background_confounders=["tank_size"],
    greedy_minimise = True # Set this to attempt further "greedy" pruning of the test case after phase 2 of CausalCut
)
minimised_test
[8]:
[(4, 'pump_on', True)]

We can see here that test minimisation has given us a test with just a single intervention at time step four. While our combinatorial optimisation gave us one at time step three, both techniques gave a minimal test case. That is, we cannot remove any intervention from this test and still observe the failure.