snp.py 10.4 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
72
    solvers = [
        "num_greedy",
        "bit_greedy",
        "num_sim_anneal",
        "num_random",
        "num_evolutionary",
    ]
Julien Lin's avatar
Julien Lin committed
73
74
75
76
77
78
79
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
    can.add_argument(
        "-m",
        "--solver",
        metavar="NAME",
        choices=solvers,
        default="num_greedy",
        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
117

Julien Lin's avatar
Julien Lin committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    can.add_argument(
        "--nb-population",
        metavar="NB",
        default=10,
        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",
        default=10,
        type=int,
        help="Number of offspring for each generation.",
    )

    can.add_argument(
Julien Lin's avatar
Julien Lin committed
143
        "--quality-threshold",
Julien Lin's avatar
Julien Lin committed
144
        metavar="DVAL",
Julien Lin's avatar
Julien Lin committed
145
146
147
        default=600,
        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
148
149
    )

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


Julien Lin's avatar
Julien Lin committed
153
def run_algorithm(the, iters_func):
Julien Lin's avatar
Julien Lin committed
154
    val, sol, sensors = None, None, None
Johann Dreo's avatar
Johann Dreo committed
155
    if the.solver == "num_greedy":
Julien Lin's avatar
Julien Lin committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        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
173
            iters_func,
Julien Lin's avatar
Julien Lin committed
174
        )
Johann Dreo's avatar
Johann Dreo committed
175
176
177
        sensors = num.to_sensors(sol)

    elif the.solver == "bit_greedy":
Julien Lin's avatar
Julien Lin committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
        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
195
            iters_func,
Julien Lin's avatar
Julien Lin committed
196
197
        )
        sensors = bit.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
198
    elif the.solver == "num_sim_anneal":
Julien Lin's avatar
Julien Lin committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        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
220
            iters_func,
Julien Lin's avatar
Julien Lin committed
221
222
        )
        sensors = num.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
223

Julien Lin's avatar
Julien Lin committed
224
    elif the.solver == "bit_sim_anneal":
Julien Lin's avatar
Julien Lin committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        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.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
242
243
244
            make.temp(0.99),
            make.proba(),
            make.rand(),
Julien Lin's avatar
Julien Lin committed
245
            iters_func,
Julien Lin's avatar
Julien Lin committed
246
247
        )
        sensors = num.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
248
249
250
251
252
253
254
255
256
257
258
259
260
    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
261
            iters_func,
Julien Lin's avatar
Julien Lin committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        )
        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
284
285
286
                domain_width=the.domain_width,
                variation_scale=the.variation_scale,
                nb_sensors=the.nb_sensors,
Julien Lin's avatar
Julien Lin committed
287
288
289
290
291
292
            ),
            make.replacement(
                num.replacement,
                nb_next_generation=the.nb_selected,
                strat=None,
            ),
Julien Lin's avatar
Julien Lin committed
293
            iters_func,
Julien Lin's avatar
Julien Lin committed
294
295
        )
        sensors = num.to_sensors(sol)
Julien Lin's avatar
Julien Lin committed
296
297
    return val, sol, sensors

Julien Lin's avatar
Julien Lin committed
298

Julien Lin's avatar
Julien Lin committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
325
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
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
363
    val, sol, sensors = run_algorithm(the, iters_func)
Julien Lin's avatar
Julien Lin committed
364

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

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

Julien Lin's avatar
Julien Lin committed
370
371
372
373
    should_plot = False
    if should_plot:
        plot_sol(the, history, sensors, shape)

374
375
376
377
378
379
380
381
382
383
384
385
386
387
    # coefficient when objective function is called multiples times in one epoch
    coef = get_coef_objective_func(the)

    # 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


def get_constant_objectiv_func(the):
    return the.nb_population if the.solver == "num_evolutionary" else 0


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


Julien Lin's avatar
Julien Lin committed
390
391
if __name__ == "__main__":

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