| 1 | --- |
| 2 | tags: technical, python, example, properties |
| 3 | date: 2016-05-29 21:00 |
| 4 | title: Testing Optimizers |
| 5 | author: drmaciver |
| 6 | redirect_from: /articles/testing-optimizers |
| 7 | --- |
| 8 | |
| 9 | We've [previously looked into testing performance optimizations](../testing-performance-optimizations/) |
| 10 | using Hypothesis, but this |
| 11 | article is about something quite different: It's about testing code |
| 12 | that is designed to optimize a value. That is, you have some function |
| 13 | and you want to find arguments to it that maximize (or minimize) its |
| 14 | value. |
| 15 | |
| 16 | As well as being an interesting subject in its own right, this will also |
| 17 | nicely illustrate the use of Hypothesis's data() functionality, which |
| 18 | allows you to draw more data after the test has started, and will |
| 19 | introduce a useful general property that can improve your testing in |
| 20 | a much wider variety of settings. |
| 21 | |
| 22 | <!--more--> |
| 23 | |
| 24 | We'll use [the Knapsack Packing Problem](https://en.wikipedia.org/wiki/Knapsack_problem) |
| 25 | as our example optimizer. We'll use the greedy approximation algorithm |
| 26 | described in the link, and see if Hypothesis can show us that it's |
| 27 | merely an approximation and not in fact optimal. |
| 28 | |
| 29 | ```python |
| 30 | def pack_knapsack(items, capacity): |
| 31 | """Given items as a list [(value, weight)], with value and weight |
| 32 | strictly positive integers, try to find a maximum value subset of |
| 33 | items with total weight <= capacity""" |
| 34 | remaining_capacity = capacity |
| 35 | result = [] |
| 36 | |
| 37 | # Sort in order of decreasing value per unit weight, breaking |
| 38 | # ties by taking the lowest weighted items first. |
| 39 | items = sorted(items, key=lambda x: (x[1] / x[0], x[1])) |
| 40 | for value, weight in items: |
| 41 | if weight <= remaining_capacity: |
| 42 | result.append((value, weight)) |
| 43 | remaining_capacity -= weight |
| 44 | return result |
| 45 | ``` |
| 46 | |
| 47 | So how are we going to test this? |
| 48 | |
| 49 | If we had another optimizer we could test by comparing the two results, |
| 50 | but we don't, so we need to figure out properties it should satisfy in |
| 51 | the absence of that. |
| 52 | |
| 53 | The trick we will used to test this is to look for responses to change. |
| 54 | |
| 55 | That is, we will run the function, we will make a change to the data |
| 56 | that should cause the function's output to change in a predictable way, |
| 57 | and then we will run the function again and see if it did. |
| 58 | |
| 59 | But how do we figure out what changes to make? |
| 60 | |
| 61 | The key idea is that we will look at the output of running the optimizer |
| 62 | and use that to guide what changes we make. In particular we will test |
| 63 | the following two properties: |
| 64 | |
| 65 | 1. If we remove an item that was previously chosen as part of the |
| 66 | optimal solution, this should not improve the score. |
| 67 | 2. If we add an extra copy of an item that was previously chosen as part |
| 68 | of the optimal solution, this should not make the score worse. |
| 69 | |
| 70 | In the first case, any solution that is found when running with one |
| 71 | fewer item would also be a possible solution when running with the full |
| 72 | set, so if the optimizer is working correctly then it should have found |
| 73 | that one if it were an improvement. |
| 74 | |
| 75 | In the second case, the opposite is true: Any solution that was |
| 76 | previously available is still available, so if the optimizer is working |
| 77 | correctly it can't find a worse one than it previously found. |
| 78 | |
| 79 | The two tests look very similar: |
| 80 | |
| 81 | ```python |
| 82 | from hypothesis import Verbosity, assume, given, settings, strategies as st |
| 83 | |
| 84 | |
| 85 | def score_items(items): |
| 86 | return sum(value for value, _ in items) |
| 87 | |
| 88 | |
| 89 | PositiveIntegers = st.integers(min_value=1, max_value=10) |
| 90 | Items = st.lists(st.tuples(PositiveIntegers, PositiveIntegers), min_size=1) |
| 91 | Capacities = PositiveIntegers |
| 92 | |
| 93 | |
| 94 | @given(Items, Capacities, st.data()) |
| 95 | def test_cloning_an_item(items, capacity, data): |
| 96 | original_solution = pack_knapsack(items, capacity) |
| 97 | assume(original_solution) |
| 98 | items.append(data.draw(st.sampled_from(original_solution))) |
| 99 | new_solution = pack_knapsack(items, capacity) |
| 100 | assert score_items(new_solution) >= score_items(original_solution) |
| 101 | |
| 102 | |
| 103 | @given(Items, Capacities, st.data()) |
| 104 | def test_removing_an_item(items, capacity, data): |
| 105 | original_solution = pack_knapsack(items, capacity) |
| 106 | assume(original_solution) |
| 107 | item = data.draw(st.sampled_from(original_solution)) |
| 108 | items.remove(item) |
| 109 | new_solution = pack_knapsack(items, capacity) |
| 110 | assert score_items(new_solution) <= score_items(original_solution) |
| 111 | ``` |
| 112 | |
| 113 | (The max_value parameter for integers is inessential but results in |
| 114 | nicer example quality). |
| 115 | |
| 116 | The *data* strategy simply provides an object you can use for drawing |
| 117 | more data interactively during the test. This allows us to make our |
| 118 | choices dependent on the output of the function when we run it. The |
| 119 | draws made will be printed as additional information in the case of a |
| 120 | failing example. |
| 121 | |
| 122 | In fact, both of these tests fail: |
| 123 | |
| 124 | ``` |
| 125 | |
| 126 | Falsifying example: test_cloning_an_item(items=[(1, 1), (1, 1), (2, 5)], capacity=7, data=data(...)) |
| 127 | Draw 1: (1, 1) |
| 128 | |
| 129 | ``` |
| 130 | |
| 131 | In this case what happens is that when Hypothesis clones an item of |
| 132 | weight and value 1, the algorithm stuffs its knapsack with all three |
| 133 | (1, 1) items, at which point it has spare capacity but no remaining |
| 134 | items that are small enough to fit in it. |
| 135 | |
| 136 | ``` |
| 137 | |
| 138 | Falsifying example: test_removing_a_chosen_item(items=[(1, 1), (2, 4), (1, 2)], capacity=6, data=data(...)) |
| 139 | Draw 1: (1, 1) |
| 140 | |
| 141 | ``` |
| 142 | |
| 143 | In this case what happens is the opposite: Previously the greedy |
| 144 | algorithm was reaching for the (1, 1) item as the most appealing because |
| 145 | it had the highest value to weight ratio, but by including it it only |
| 146 | had space for one of the remaining two. When Hypothesis removed that |
| 147 | option, it could fit the remaining two items into its knapsack and thus |
| 148 | scored a higher point. |
| 149 | |
| 150 | In this case these failures were more or less expected: As described in |
| 151 | the Wikipedia link, for the relatively small knapsacks we're exploring |
| 152 | here the greedy approximation algorithm turns out to in fact be quite |
| 153 | bad, and Hypothesis can easily expose that. |
| 154 | |
| 155 | This technique however can be more widely applied: e.g. You can try |
| 156 | changing permissions and settings on a user and asserting that they |
| 157 | always have more options, or increasing the capacity of a subsystem and |
| 158 | seeing that it is always allocated more tasks. |