snp.py 10.5 KB
Newer Older
Julien Lin's avatar
Julien Lin committed
1
# encoding: utf-8
nojhan's avatar
nojhan committed
2
import math
Julien Lin's avatar
Julien Lin committed
3
from typing import Any
Johann Dreo's avatar
Johann Dreo committed
4
5
import numpy as np
import matplotlib.pyplot as plt
Julien Lin's avatar
Julien Lin committed
6
import argparse
Johann Dreo's avatar
Johann Dreo committed
7
8
9

from sho import make, algo, iters, plot, num, bit, pb

Julien Lin's avatar
Julien Lin committed
10
11
12
# Dimension of the search space.
d = 2

Johann Dreo's avatar
Johann Dreo committed
13
14
15
16
########################################################################
# Interface
########################################################################

Julien Lin's avatar
Julien Lin committed
17

Julien Lin's avatar
Julien Lin committed
18
def get_args_parser():
Johann Dreo's avatar
Johann Dreo committed
19
20
    can = argparse.ArgumentParser()

Julien Lin's avatar
Julien Lin committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    can.add_argument(
        "-n",
        "--nb-sensors",
        metavar="NB",
        default=3,
        type=int,
        help="Number of sensors",
    )

    can.add_argument(
        "-r",
        "--sensor-range",
        metavar="RATIO",
        default=0.3,
        type=float,
        help="Sensors' range (as a fraction of domain width, max is √2)",
    )

    can.add_argument(
        "-w",
        "--domain-width",
        metavar="NB",
        default=30,
        type=int,
        help="Domain width (a number of cells). If you change this you will probably need to update `--target` accordingly",
    )

    can.add_argument(
        "-i",
        "--iters",
        metavar="NB",
        default=100,
        type=int,
        help="Maximum number of iterations",
    )

    can.add_argument(
        "-s",
        "--seed",
        metavar="VAL",
        default=None,
        type=int,
        help="Random pseudo-generator seed (none for current epoch)",
    )

Julien Lin's avatar
Julien Lin committed
66
67
68
69
70
71
    solvers = [
        "num_greedy",
        "bit_greedy",
        "num_sim_anneal",
        "num_random",
        "num_evolutionary",
Julien Lin's avatar
Julien Lin committed
72
        "bit_sim_anneal"
Julien Lin's avatar
Julien Lin committed
73
    ]
Julien Lin's avatar
Julien Lin committed
74
75
76
77
78
    can.add_argument(
        "-m",
        "--solver",
        metavar="NAME",
        choices=solvers,
Julien Lin's avatar
Julien Lin committed
79
        default="num_evolutionary",
Julien Lin's avatar
Julien Lin committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        help="Solver to use, among: " + ", ".join(solvers),
    )

    can.add_argument(
        "-t",
        "--target",
        metavar="VAL",
        default=30 * 30,
        type=float,
        help="Objective function value target",
    )

    can.add_argument(
        "-y",
        "--steady-delta",
        metavar="NB",
        default=50,
        type=float,
        help="Stop if no improvement after NB iterations",
    )

    can.add_argument(
        "-e",
        "--steady-epsilon",
        metavar="DVAL",
        default=0,
        type=float,
        help="Stop if the improvement of the objective function value is lesser than DVAL",
    )

    can.add_argument(
        "-a",
        "--variation-scale",
        metavar="RATIO",
        default=0.3,
        type=float,
        help="Scale of the variation operators (as a ration of the domain width)",
    )
Johann Dreo's avatar
Johann Dreo committed
118

Julien Lin's avatar
Julien Lin committed
119
120
121
    can.add_argument(
        "--nb-population",
        metavar="NB",
Julien Lin's avatar
Julien Lin committed
122
        default=100,
Julien Lin's avatar
Julien Lin committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        type=int,
        help="Size of the initial population for evolutionary algorithm.",
    )

    can.add_argument(
        "--nb-selected",
        metavar="NB",
        type=int,
        default=10,
        help="Number of selected individuals before each generation.",
    )

    can.add_argument(
        "--nb-offspring",
        metavar="NB",
Julien Lin's avatar
Julien Lin committed
138
        default=100,
Julien Lin's avatar
Julien Lin committed
139
140
141
142
143
        type=int,
        help="Number of offspring for each generation.",
    )

    can.add_argument(
Julien Lin's avatar
Julien Lin committed
144
        "--quality-threshold",
Julien Lin's avatar
Julien Lin committed
145
        metavar="DVAL",
Julien Lin's avatar
Julien Lin committed
146
        default=660,
Julien Lin's avatar
Julien Lin committed
147
148
        type=float,
        help="Quality threshold. Used to plot the probability of a run being under the quality threshold.",
Julien Lin's avatar
Julien Lin committed
149
150
    )

Julien Lin's avatar
Julien Lin committed
151
    return can
Johann Dreo's avatar
Johann Dreo committed
152
153


Julien Lin's avatar
Julien Lin committed
154
def run_algorithm(the, iters_func):
Julien Lin's avatar
Julien Lin committed
155
    val, sol, sensors = None, None, None
Johann Dreo's avatar
Johann Dreo committed
156
    if the.solver == "num_greedy":
Julien Lin's avatar
Julien Lin committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        val, sol = algo.greedy(
            make.func(
                num.cover_sum,
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
                num.rand,
                dim=d * the.nb_sensors,
                scale=the.domain_width,
            ),
            make.neig(
                num.neighb_square,
                scale=the.variation_scale,
                domain_width=the.domain_width,
            ),
Julien Lin's avatar
Julien Lin committed
174
            iters_func,
Julien Lin's avatar
Julien Lin committed
175
        )
Johann Dreo's avatar
Johann Dreo committed
176
177
178
        sensors = num.to_sensors(sol)

    elif the.solver == "bit_greedy":
Julien Lin's avatar
Julien Lin committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        val, sol = algo.greedy(
            make.func(
                bit.cover_sum,
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
                bit.rand,
                domain_width=the.domain_width,
                nb_sensors=the.nb_sensors,
            ),
            make.neig(
                bit.neighb_square,
                scale=the.variation_scale,
                domain_width=the.domain_width,
            ),
Julien Lin's avatar
Julien Lin committed
196
            iters_func,
Julien Lin's avatar
Julien Lin committed
197
198
        )
        sensors = bit.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
199
    elif the.solver == "num_sim_anneal":
Julien Lin's avatar
Julien Lin committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        val, sol = algo.simulated_annealing(
            make.func(
                num.cover_sum,
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
                num.init_with_t,
                t=2000,
                dim=d * the.nb_sensors,
                scale=the.domain_width,
            ),
            make.neig(
                num.neighb_square,
                scale=the.variation_scale,
                domain_width=the.domain_width,
            ),
            make.temp(0.99),
            make.proba(),
            make.rand(),
Julien Lin's avatar
Julien Lin committed
221
            iters_func,
Julien Lin's avatar
Julien Lin committed
222
223
        )
        sensors = num.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
224

Julien Lin's avatar
Julien Lin committed
225
    elif the.solver == "bit_sim_anneal":
Julien Lin's avatar
Julien Lin committed
226
227
        val, sol = algo.simulated_annealing(
            make.func(
Julien Lin's avatar
Julien Lin committed
228
                bit.cover_sum,
Julien Lin's avatar
Julien Lin committed
229
230
231
232
233
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
Julien Lin's avatar
Julien Lin committed
234
235
236
237
                bit.init_with_t,
                t=2000,
                domain_width=the.domain_width,
                nb_sensors=the.nb_sensors,
Julien Lin's avatar
Julien Lin committed
238
239
            ),
            make.neig(
Julien Lin's avatar
Julien Lin committed
240
                bit.neighb_square,
Julien Lin's avatar
Julien Lin committed
241
242
243
                scale=the.variation_scale,
                domain_width=the.domain_width,
            ),
Julien Lin's avatar
Julien Lin committed
244
245
246
            make.temp(0.99),
            make.proba(),
            make.rand(),
Julien Lin's avatar
Julien Lin committed
247
            iters_func,
Julien Lin's avatar
Julien Lin committed
248
        )
Julien Lin's avatar
Julien Lin committed
249
        sensors = bit.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
250
251
252
253
254
255
256
257
258
259
260
261
262
    elif the.solver == "num_random":
        val, sol = algo.random(
            make.func(
                num.cover_sum,
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
                num.rand,
                dim=d * the.nb_sensors,
                scale=the.domain_width,
            ),
Julien Lin's avatar
Julien Lin committed
263
            iters_func,
Julien Lin's avatar
Julien Lin committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        )
        sensors = num.to_sensors(sol)
    elif the.solver == "num_evolutionary":
        val, sol = algo.evolutionary(
            make.func(
                num.cover_sum,
                domain_width=the.domain_width,
                sensor_range=the.sensor_range,
                dim=d * the.nb_sensors,
            ),
            make.init(
                num.init_evolutionary,
                dim=d * the.nb_sensors,
                scale=the.domain_width,
                nb_population=the.nb_population,
            ),
            num.best,
            make.selection(num.selection, nb_selected=the.nb_selected),
            num.evaluate,
            make.variation(
                num.variation,
                nb_offspring=the.nb_offspring,
Julien Lin's avatar
Julien Lin committed
286
287
288
                domain_width=the.domain_width,
                variation_scale=the.variation_scale,
                nb_sensors=the.nb_sensors,
Julien Lin's avatar
Julien Lin committed
289
290
291
292
293
294
            ),
            make.replacement(
                num.replacement,
                nb_next_generation=the.nb_selected,
                strat=None,
            ),
Julien Lin's avatar
Julien Lin committed
295
            iters_func,
Julien Lin's avatar
Julien Lin committed
296
297
        )
        sensors = num.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
298
299
    return val, sol, sensors

Julien Lin's avatar
Julien Lin committed
300

Julien Lin's avatar
Julien Lin committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def plot_sol(the, history, sensors, shape):
    fig = plt.figure()

    if the.nb_sensors == 1 and the.domain_width <= 50:
        ax1 = fig.add_subplot(121, projection="3d")
        ax2 = fig.add_subplot(122)

        f = make.func(
            num.cover_sum,
            domain_width=the.domain_width,
            sensor_range=the.sensor_range,
            dim=d * the.nb_sensors,
        )
        plot.surface(ax1, shape, f)
        plot.path(ax1, shape, history)
    else:
        ax2 = fig.add_subplot(121)

    domain = np.zeros(shape)
    domain = pb.coverage(domain, sensors, the.sensor_range * the.domain_width)
    domain = plot.highlight_sensors(domain, sensors)
    ax2.imshow(domain)

    plt.show()

Julien Lin's avatar
Julien Lin committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364

def main(args=None):
    can = get_args_parser()

    the = can.parse_args(args)

    # Minimum checks.
    assert 0 < the.nb_sensors
    assert 0 < the.sensor_range <= math.sqrt(2)
    assert 0 < the.domain_width
    assert 0 < the.iters

    # Do not forget the seed option,
    # in case you would start "runs" in parallel.
    np.random.seed(the.seed)

    # Weird numpy way to ensure single line print of array.
    np.set_printoptions(linewidth=np.inf)  # type: ignore

    # Common termination and checkpointing.
    history: list[Any] = []
    iters_func = make.iter(
        iters.several,
        agains=[
            make.iter(iters.max, nb_it=the.iters),
            make.iter(
                iters.save, filename=the.solver + ".csv", fmt="{it} ; {val} ; {sol}\n"
            ),
            make.iter(iters.log, fmt="\r{it} {val}"),
            make.iter(iters.history, history=history),
            make.iter(iters.target, target=the.target),
            iters.steady(the.steady_delta, the.steady_epsilon),
        ],
    )

    # Erase the previous file.
    with open(the.solver + ".csv", "w") as fd:
        fd.write("# {} {}\n".format(the.solver, the.domain_width))

Julien Lin's avatar
Julien Lin committed
365
    val, sol, sensors = run_algorithm(the, iters_func)
Julien Lin's avatar
Julien Lin committed
366

Johann Dreo's avatar
Johann Dreo committed
367
    # Fancy output.
Julien Lin's avatar
Julien Lin committed
368
    print("\n{} : {}".format(val, sensors))
Johann Dreo's avatar
Johann Dreo committed
369

Julien Lin's avatar
Julien Lin committed
370
    shape = (the.domain_width, the.domain_width)
Johann Dreo's avatar
Johann Dreo committed
371

Julien Lin's avatar
Julien Lin committed
372
373
374
    should_plot = False
    if should_plot:
        plot_sol(the, history, sensors, shape)
Johann Dreo's avatar
Johann Dreo committed
375

376
377
    # coefficient when objective function is called multiples times in one epoch
    coef = get_coef_objective_func(the)
Johann Dreo's avatar
Johann Dreo committed
378

379
380
381
    # constant when objective function is called multiples times in one epoch
    initial = get_constant_objectiv_func(the)
    return val, len(history) * coef + initial, sol, sensors
Julien Lin's avatar
Julien Lin committed
382
383


384
385
def get_constant_objectiv_func(the):
    return the.nb_population if the.solver == "num_evolutionary" else 0
Johann Dreo's avatar
Johann Dreo committed
386
387


388
def get_coef_objective_func(the):
Julien Lin's avatar
Julien Lin committed
389
    return the.nb_offspring if the.solver == "num_evolutionary" else 1
Julien Lin's avatar
Julien Lin committed
390
391
392
393


if __name__ == "__main__":

Julien Lin's avatar
Julien Lin committed
394
    main()