Tests that restarting clears the history of recent solutions and starts over from scratch.
(ok_small)
| 184 | |
| 185 | |
| 186 | def test_restart(ok_small): |
| 187 | """ |
| 188 | Tests that restarting clears the history of recent solutions and starts |
| 189 | over from scratch. |
| 190 | """ |
| 191 | Params = IteratedLocalSearchParams |
| 192 | |
| 193 | sols = [ |
| 194 | Solution(ok_small, [[1, 3], [2, 4]]), # 22065 (infeas) |
| 195 | Solution(ok_small, [[1, 2], [3, 4]]), # 9725 |
| 196 | Solution(ok_small, [[1, 2], [3, 4]]), # 9725 |
| 197 | Solution(ok_small, [[1, 2], [4, 3]]), # 9868 |
| 198 | ] |
| 199 | |
| 200 | def run(params: IteratedLocalSearchParams): # run with given params |
| 201 | idx = iter(range(len(sols))) |
| 202 | ils = IteratedLocalSearch( |
| 203 | ok_small, |
| 204 | PenaltyManager(initial_penalties=([20], 6, 6)), |
| 205 | RandomNumberGenerator(42), |
| 206 | lambda *_, **kw: sols[next(idx)], # returns sols one at a time |
| 207 | sols[0], |
| 208 | params, |
| 209 | ) |
| 210 | |
| 211 | res = ils.run(MaxIterations(len(sols))) |
| 212 | return res.stats.data |
| 213 | |
| 214 | # First run without a restart. We look back to the current solution from |
| 215 | # last iteration, which means that we only accept improving solutions. |
| 216 | curr_costs = [22065, 9725, 9725, 9725] |
| 217 | params = Params(history_length=1, exhaustive_on_best=False) |
| 218 | assert_equal([datum.current_cost for datum in run(params)], curr_costs) |
| 219 | |
| 220 | # But here a restart occurs in the third iteration, and that should clear |
| 221 | # the history. We now accept the worsening solution in the last iteration. |
| 222 | params = Params( |
| 223 | num_iters_no_improvement=1, |
| 224 | history_length=1, |
| 225 | exhaustive_on_best=False, |
| 226 | ) |
| 227 | curr_costs = [22065, 9725, 9725, 9868] |
| 228 | assert_equal([datum.current_cost for datum in run(params)], curr_costs) |
| 229 | |
| 230 | |
| 231 | def test_exhaustive_search_on_new_best_solution(ok_small): |