{ "cells": [ { "cell_type": "markdown", "id": "8d558026-1ab1-4f5c-8df5-d1f2b505a0ec", "metadata": {}, "source": [ "# Test Minimisation with CausalCut\n", "\n", "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.\n", "\n", "## Motivating Example\n", "Consider a controller system for a slow release water tank.\n", "The system has an inlet pump, an outlet valve, and a sensor to measure the level.\n", "The tank initially starts empty, with the outlet valve is closed, and the inlet pump switched off.\n", "The controller then has the following dynamics:\n", "\n", "- If the tank level falls to 20% of its capacity, the inlet pump is switched on.\n", "- When the tank reaches 70% capacity, the pump is switched off.\n", "- If the tank ever reaches 90% capacity, the outlet valve is opened.\n", "- When the tank level falls to 30% capacity, the outlet valve is closed." ] }, { "cell_type": "code", "execution_count": 1, "id": "be2f77c9-337e-46f0-acb2-47beb9d06558", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
timetank_levelpump_onvalve_opentank_size
000.0FalseFalse10
110.0TrueFalse10
223.0TrueFalse10
335.9TrueFalse10
448.8FalseFalse10
558.7FalseFalse10
668.6FalseFalse10
778.5FalseFalse10
888.4FalseFalse10
998.3FalseFalse10
\n", "
" ], "text/plain": [ " time tank_level pump_on valve_open tank_size\n", "0 0 0.0 False False 10\n", "1 1 0.0 True False 10\n", "2 2 3.0 True False 10\n", "3 3 5.9 True False 10\n", "4 4 8.8 False False 10\n", "5 5 8.7 False False 10\n", "6 6 8.6 False False 10\n", "7 7 8.5 False False 10\n", "8 8 8.4 False False 10\n", "9 9 8.3 False False 10" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "class SimpleTank():\n", " def __init__(self, tank_size:int, tank_level: float = 0, pump_on: bool = False, valve_open:bool = False):\n", " self.time = 0\n", " self.tank_level = tank_level\n", " self.pump_on = pump_on\n", " self.valve_open = valve_open\n", " self.tank_size = tank_size\n", "\n", " def tick(self):\n", " # Time actions\n", " self.time += 1\n", " if self.tank_level > 0.1:\n", " if self.valve_open:\n", " self.tank_level -= 1\n", " else:\n", " # Slow release\n", " self.tank_level -= 0.1\n", " if self.pump_on:\n", " self.tank_level += 3\n", "\n", " # Set actuators based on sensor values \n", " if self.tank_level >= 0.7 * self.tank_size:\n", " self.pump_on = False\n", " if self.tank_level >= 0.9 * self.tank_size:\n", " self.valve_open = True\n", " if self.tank_level <= 0.3 * self.tank_size:\n", " self.valve_open = False\n", " if self.tank_level <= 0.2 * self.tank_size:\n", " self.pump_on = True\n", "\n", " \n", " def state(self):\n", " return {\n", " \"time\": self.time,\n", " \"tank_level\": self.tank_level,\n", " \"pump_on\": self.pump_on,\n", " \"valve_open\": self.valve_open,\n", " \"tank_size\": self.tank_size,\n", " }\n", " \n", "\n", "def run_pump(time_steps:int):\n", " simple_tank = SimpleTank(tank_size=10)\n", " data = []\n", " for step in range(time_steps):\n", " data.append(simple_tank.state())\n", " simple_tank.tick()\n", " return pd.DataFrame(data)\n", "\n", "run_pump(10)" ] }, { "cell_type": "markdown", "id": "134b65bb-5a2e-4e46-addb-b80197122b2f", "metadata": {}, "source": [ "Unlike traditional software, this is a _hybrid_ system that involves interaction between digital software and the real world via sensors and actuators.\n", "Sensors provide us with a continuous stream of values which change over time (the level of the tank).\n", "Actuators (in this case, the pump and the valve) can be turned on or off by the system in response to sensor readings.\n", "In turn, the state of the actuators then goes on to influence subsequent sensor readings.\n", "\n", "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)`.\n", "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.\n", "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.\n", "We can express this as follows:" ] }, { "cell_type": "code", "execution_count": 2, "id": "70971e80-955d-4ac1-9ff4-b61bf87387f2", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 'pump_on', True),\n", " (2, 'pump_on', True),\n", " (3, 'pump_on', True),\n", " (4, 'pump_on', True)]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "test_case = [(time_step, \"pump_on\", True) for time_step in range(1, 5)]\n", "test_case" ] }, { "cell_type": "markdown", "id": "f441f56d-8251-442a-ae58-0b53e10525f3", "metadata": {}, "source": [ "To execute this test case on the tank system, we can define a modified version of `run_pump`:" ] }, { "cell_type": "code", "execution_count": 3, "id": "717c22e8-f629-4390-8314-4619267a5408", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
timetank_levelpump_onvalve_opentank_size
000.0FalseFalse10
110.0TrueFalse10
223.0TrueFalse10
335.9TrueFalse10
448.8TrueFalse10
5511.7TrueTrue10
6613.7FalseTrue10
7712.7FalseTrue10
8811.7FalseTrue10
9910.7FalseTrue10
\n", "
" ], "text/plain": [ " time tank_level pump_on valve_open tank_size\n", "0 0 0.0 False False 10\n", "1 1 0.0 True False 10\n", "2 2 3.0 True False 10\n", "3 3 5.9 True False 10\n", "4 4 8.8 True False 10\n", "5 5 11.7 True True 10\n", "6 6 13.7 False True 10\n", "7 7 12.7 False True 10\n", "8 8 11.7 False True 10\n", "9 9 10.7 False True 10" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def run_pump_test(time_steps:int, interventions:list[tuple[int, str, bool]], tank_size:int = 10):\n", " simple_tank = SimpleTank(tank_size=tank_size)\n", " data = []\n", " for step in range(time_steps):\n", " data.append(simple_tank.state())\n", " simple_tank.tick()\n", " # Apply the interventions for each time step\n", " for time, var, val in interventions:\n", " if time == step:\n", " setattr(simple_tank, var, val)\n", " return pd.DataFrame(data)\n", "\n", "# Keep the pump on for the first 4 time steps\n", "# The 0th time step here represents the initial state, which we cannot intervene on\n", "run_pump_test(time_steps=10, interventions=test_case)" ] }, { "cell_type": "markdown", "id": "9b413720-dae2-44eb-86cb-32d32eb910bc", "metadata": {}, "source": [ "## Test Minimisation\n", "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.\n", "However, we may not need all four `pump_on` interventions to achieve this.\n", "The question then is \"Which interventions were actually necessary to cause the failure?\"\n", "This is exactly the question that [CausalCut](https://doi.org/10.1145/3816435) is intended to answer.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 4, "id": "5e1ccf3e-7f28-44a3-ad31-cc21ad9275b4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(3, 'pump_on', True)]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from itertools import chain, combinations\n", "\n", "def powerset(iterable):\n", " \"\"\"\n", " Subsequences of the iterable from shortest to longest.\n", " \"\"\"\n", " # powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\n", " s = list(iterable)\n", " return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))\n", "\n", "def find_minimal_test():\n", " \"\"\"\n", " Try every subset of interventions from the test case from shortest to longest.\n", " \"\"\"\n", " for interventions in powerset(test_case):\n", " df = run_pump_test(time_steps=10, interventions=interventions)\n", " if (df[\"tank_level\"] > df[\"tank_size\"]).any():\n", " return list(interventions)\n", "\n", "find_minimal_test()" ] }, { "cell_type": "markdown", "id": "cb1cef47-ae52-451e-9205-c85acf77f33e", "metadata": {}, "source": [ "We see here that we only need a single intervention to force an overflow here.\n", "However, for more complex systems that take a long time to run, it may be prohibitive to check every combination.\n", "This is where the two-step minimisation approach of CausalCut comes in.\n", "\n", "- 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.\n", "- In the second phase, CausalCut iteritively re-adds the pruned interventions in order of their estimated causal contribution until the original failure is produced.\n", "\n", "For a detailed explanation of the algorithm, we refer the users to the API documentation or [this paper](https://doi.org/10.1145/3816435)." ] }, { "cell_type": "markdown", "id": "a85e9a0c-8437-4b53-8bdf-5199cd4104fe", "metadata": {}, "source": [ "## Causal Graph\n", "\n", "As with all causal testing, we need to specify the causal relationships within the system.\n", "This is a little different from the rest of how the Causal Testing Framework operates because we have feedback between variables over time.\n", "Where the rest of the framework assumes an acyclic causal structure, this is exactly what we have here.\n", "\n", "![Causal structure of the simple tank system with feedback cycles](dcg.dot.png)" ] }, { "cell_type": "markdown", "id": "f91081a2-8ee9-4695-9e1d-36dffd19b1fa", "metadata": {}, "source": [ "## Data Collection\n", "\n", "The first phase of CausalCut intolves using pre-existing data to estimate the causal contribution of each event to a failure.\n", "This involves inverting the value of each intervention individually and comparing the new \"treatment strategy\" to the original test." ] }, { "cell_type": "code", "execution_count": 5, "id": "a2a383b3-8d05-45ce-bfd2-ed61030838db", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[(1, 'pump_on', False),\n", " (2, 'pump_on', True),\n", " (3, 'pump_on', True),\n", " (4, 'pump_on', True)],\n", " [(1, 'pump_on', True),\n", " (2, 'pump_on', False),\n", " (3, 'pump_on', True),\n", " (4, 'pump_on', True)],\n", " [(1, 'pump_on', True),\n", " (2, 'pump_on', True),\n", " (3, 'pump_on', False),\n", " (4, 'pump_on', True)],\n", " [(1, 'pump_on', True),\n", " (2, 'pump_on', True),\n", " (3, 'pump_on', True),\n", " (4, 'pump_on', False)]]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sequences_to_check = []\n", "for i in range(len(test_case)):\n", " sequences_to_check.append([(time, variable, not value if index == i else value) for index, (time, variable, value) in enumerate(test_case)])\n", "sequences_to_check" ] }, { "cell_type": "markdown", "id": "7a8e3e6c-08af-4a7c-93cb-83be4590c8dd", "metadata": {}, "source": [ "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.\n", "You should then record the values of each sensor and the state of each actuator throughout the run.\n", "Data should be supplied in \"long format\", that is, with runs concatenated together to share columns." ] }, { "cell_type": "markdown", "id": "e757a207-cf75-4017-9e6a-9c55bfb90b88", "metadata": {}, "source": [ "Ideally, we would have many repeated runs for both the original test case and each \"treatment strategy\", with no other interventions.\n", "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.\n", "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." ] }, { "cell_type": "code", "execution_count": 6, "id": "b8bba3df-e33a-400b-a3e0-2c7904ec2867", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
timetank_levelpump_onvalve_opentank_sizeid
000.0FalseFalse110
110.0TrueFalse110
223.0TrueFalse110
335.9TrueFalse110
448.8FalseFalse110
.....................
558.7FalseFalse12199
668.6FalseFalse12199
778.5FalseFalse12199
888.4FalseFalse12199
998.3FalseFalse12199
\n", "

2000 rows × 6 columns

\n", "
" ], "text/plain": [ " time tank_level pump_on valve_open tank_size id\n", "0 0 0.0 False False 11 0\n", "1 1 0.0 True False 11 0\n", "2 2 3.0 True False 11 0\n", "3 3 5.9 True False 11 0\n", "4 4 8.8 False False 11 0\n", ".. ... ... ... ... ... ...\n", "5 5 8.7 False False 12 199\n", "6 6 8.6 False False 12 199\n", "7 7 8.5 False False 12 199\n", "8 8 8.4 False False 12 199\n", "9 9 8.3 False False 12 199\n", "\n", "[2000 rows x 6 columns]" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import random\n", "random.seed(1)\n", "TIME_STEPS=10\n", "\n", "def collect_data():\n", " \"\"\"\n", " Collect some random runs of the simple tank system.\n", " \"\"\"\n", " runs = []\n", " num_runs = 200\n", " for i in range(num_runs):\n", " runs.append(\n", " 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)\n", " )\n", " return pd.concat(runs)\n", "df = collect_data()\n", "df" ] }, { "cell_type": "markdown", "id": "939092be-0dfb-4501-b9b9-c490f562424f", "metadata": {}, "source": [ "## System Interaction\n", "\n", "The second phase of CausalCut involves running the system to see if the pruned sequence of interventions still yields the original failure.\n", "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." ] }, { "cell_type": "code", "execution_count": 7, "id": "cce5015a-1231-4275-a564-7b4939a297f7", "metadata": {}, "outputs": [], "source": [ "def reproduce_overflow_fault(interventions: list[tuple[int, str, bool]]):\n", " simple_tank = SimpleTank(tank_size=10)\n", " for step in range(TIME_STEPS):\n", " # Check overflow\n", " if simple_tank.tank_level > simple_tank.tank_size:\n", " return True\n", " simple_tank.tick()\n", " # Apply the interventions for each time step\n", " for time, var, val in interventions:\n", " if time == step:\n", " setattr(simple_tank, var, val)\n", " return False " ] }, { "cell_type": "markdown", "id": "eedebd0f-98ef-4b1a-ac60-f8a9e02da314", "metadata": {}, "source": [ "## Test Minimisation\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 8, "id": "6cd6aa30-37fe-4427-b564-a91c463f08eb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(4, 'pump_on', True)]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from causal_testing.minimisation.causal_cut import CausalCut\n", "from causal_testing.specification.causal_dag import CausalDAG\n", "\n", "causal_cut = CausalCut(\n", " dag=CausalDAG(\"dcg.dot\", ignore_cycles=True),\n", " df=df,\n", " safe_ranges=pd.DataFrame({\"tank_level\": {\"low\": 0, \"high\": 10}}).T,\n", " reproduce_fault=reproduce_overflow_fault\n", " )\n", "minimised_test = causal_cut.minimise_test(\n", " interventions=test_case,\n", " outcome_variable=\"tank_level\",\n", " total_time=TIME_STEPS,\n", " background_confounders=[\"tank_size\"],\n", " greedy_minimise = True # Set this to attempt further \"greedy\" pruning of the test case after phase 2 of CausalCut\n", ")\n", "minimised_test" ] }, { "cell_type": "markdown", "id": "4b02a278-a385-496c-b26f-87e460e82d66", "metadata": {}, "source": [ "We can see here that test minimisation has given us a test with just a single intervention at time step four.\n", "While our combinatorial optimisation gave us one at time step three, both techniques gave a _minimal_ test case.\n", "That is, we cannot remove any intervention from this test and still observe the failure." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.14" } }, "nbformat": 4, "nbformat_minor": 5 }