def plot_histogram(fig, ax, drone, targets, title): drones, targetss = pm.search_exhaustive(drone, targets, keep_all=True) test_drone, test_target = search_heuristic_closest(drone, targets) _cs = np.array([_d.flight_duration() for _d in drones]) _ib, _iw = np.argmin(_cs), np.argmax(_cs) _cb = drones[_ib].flight_duration() _ct = test_drone.flight_duration() print(f'optimal {_cb:.1f} s heuristic {_ct:.1f} s') _n, _b, _p = ax.hist(_cs, bins=30) ax.plot([_ct, _ct], [0, 300], label=f'heuristic ({_ct:.2f} s)') ax.plot([_cb, _cb], [0, 300], label=f'optimal ({_cb:.2f} s)') pmu.decorate(ax, title, 'time in s', 'nb sequences', True)
def plot_cpu_time(): ntargs, dts, dts2 = [2, 3, 4, 5, 6, 7, 8], [], [] for ntarg in ntargs: drone, targets = pmu.make_random_scenario(ntarg=ntarg, dp0=(0, 0), dv=15) _start = time.perf_counter() best_drone, best_seq = search_exhaustive_threshold(drone, targets) _end = time.perf_counter() dts2.append(_end - _start) print(f'{ntarg} targets thresh-> {dts2[-1]:.1f} s') _start = time.perf_counter() best_drone, best_seq = pm.search_exhaustive(drone, targets) _end = time.perf_counter() dts.append(_end - _start) print(f'{ntarg} targets -> {dts[-1]:.1f} s') plt.plot(ntargs, dts, '--o', label='Exhaustive search') plt.plot(ntargs, dts2, '--o', label='Exhaustive search with threshold') pmu.decorate(plt.gca(), 'cpu time', 'number of targets', 'time in s', True) plt.savefig('../docs/images/ex_search_time_vs_size_2.png')
def sample_solutions(filenames, nb_samples=int(1e5), force_recompute=False, use_native=True, show_2d=True): _scens = [pmu.Scenario(filename=_f) for _f in filenames] _durs = [] for _scen in _scens: cache_filename = f'/tmp/samples__{_scen.name}__{nb_samples}.npz' if force_recompute or not os.path.exists(cache_filename): print(f'sampling and storing to {cache_filename}') solver = pm_cpp_ext.Solver(_scen.drone, _scen.targets) if use_native else pm _durs.append([solver.intercept_sequence_copy(_scen.drone, np.random.permutation(_scen.targets).tolist())[1] for _i in range(nb_samples)]) np.savez(cache_filename, durs=_durs[-1]) else: print(f'loading samples from {cache_filename}') _durs.append(np.load(cache_filename)['durs']) nb_scen = len(filenames) nr, nc = nb_scen, 2 if show_2d else 1 fig = plt.figure(tight_layout=True, figsize=[6.40*nc, 2.56*nr]); fig.canvas.set_window_title("Random Sampling of Solutions") gs = fig.add_gridspec(nr, 3) axes_2d = [fig.add_subplot(gs[_i,:1]) for _i in range(nb_scen)] axes_histo = [fig.add_subplot(gs[_i,1:]) for _i in range(nb_scen)] np.set_printoptions(precision=3) for ax, _d, _scen in zip(axes_histo, _durs, _scens): _dens, _, _ = ax.hist(_d, label=f'random sampling ({nb_samples:.0e} samples)', density=True) for sol_name in ['best', 'hc', 'optimal']: try: _name, _dur, _seq = _scen.solution_by_name(sol_name) #ax.annotate(f'{sol_name}', xy=(_dur, 1))#, xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05),) ax.plot([_dur, _dur],[0, np.max(_dens)*0.8], label=f'{sol_name}: {_dur:.3f}s', alpha=0.6, linewidth=2) except KeyError: pass pmu.decorate(ax, _fmt_mmmm2(_d), xlab='time in s', legend=True) for ax, _scen in zip(axes_2d, _scens): pmu.plot_scenario(_scen, title=f'scenario: {_scen.name}', annotate=False, fig=fig, ax=ax)
def plot_search_set(cost_by_ep, seq_by_ep, epochs, window_title, skip=0): for e, c in zip(epochs[skip:], cost_by_ep[skip:]): plt.hist(c, label=f'{e/1000} k epochs', alpha=0.6) pmu.decorate(plt.gca(), title=window_title, xlab='time in s', legend=True) plt.gcf().canvas.set_window_title(window_title)
def plot_search_chronograms(filename, epoch, nrun, force=False): scen = pmu.Scenario(filename=filename) # set of quasi lin #Ts = [lambda i: pm_sa._f1(2, epoch/10, 1e-2, 9*epoch/10, i)]*5 # set of quasi lin #Ts = [lambda i: pm_sa._f1(5, epoch/10, 1e-2, 9*epoch/10, i), lambda i: pm_sa._f1(2, epoch/10, 1e-2, 9*epoch/10, i), lambda i: pm_sa._f1(1, epoch/10, 1e-2, 9*epoch/10, i)] #Ts = [lambda i: pm_sa._f1(2, epoch/10, 1e-2, 9*epoch/10, i), lambda i: pm_sa._f1(1, epoch/10, 1e-2, 9*epoch/10, i)] # lin vs quasi lin #Ts = [lambda i: pm_sa._aff(2, 1e-2, epoch, i), lambda i: pm_sa._f1(2, epoch/10, 1e-2, 9*epoch/10, i), lambda i: pm_sa._f1(2, 0, 1e-2, 9*epoch/10, i)] #Ts = [lambda i: pm_sa._aff(2, 0.01, epoch, i), lambda i: pm_sa._f1(2, epoch/10, 1e-2, 9*epoch/10, i)] ##Ts = [lambda i: pm_sa._aff(1, 1e-2, epoch, i), lambda i: pm_sa._f1(1, 0, 1e-2, 0.9*epoch, i), lambda i: pm_sa._f1(1, 0, 1e-2, 0.8*epoch, i)] # set of lin #Ts = [(lambda i: pm_sa._f1(T0, 0., 1e-2, 0.8*epoch, i)) for T0 in [5, 2, 1,]] Ts = [lambda i: pm_sa._f1(1, 0., 1e-2, 0.8*epoch, i), lambda i: pm_sa._f1(2, 0., 1e-2, 0.8*epoch, i), lambda i: pm_sa._f1(3, 0., 1e-2, 0.8*epoch, i), lambda i: pm_sa._f1(5, 0., 1e-2, 0.8*epoch, i)] #Ts = [lambda i: pm_sa._aff(5, 1e-2, epoch, i), lambda i: pm_sa._aff(2, 1e-2, epoch, i), lambda i: pm_sa._aff(1, 1e-2, epoch, i)] # step #Ts = [lambda i: pm_sa._aff(1, 1e-2, epoch, i), lambda i: pm_sa._step(1, 1e-2, epoch/2, i)] # 2 aff #Ts = [lambda i: pm_sa._2aff(1, 1e-2, epoch/2, 0.5, 1e-2, epoch, i)] #Ts = [lambda i: pm_sa._aff(1, 1e-2, epoch, i), lambda i: pm_sa._2aff(1, 1e-2, 2*epoch/3, 0.25, 1e-2, epoch, i), lambda i: pm_sa._f1(1, 0, 1e-2, 2*epoch/3, i)] # lin vs exp #Ts = [lambda i: pm_sa._aff(2, 0.01, epoch, i), lambda i: pm_sa._exp(2, epoch/2, i), lambda i: pm_sa._exp(2, epoch/3, i)] # default lin #Ts = [lambda i: pm_sa._aff(1, 1e-2, epoch, i)] cache_filename = f'/tmp/psc_{scen.name}_{epoch}.npz' if force or not os.path.exists(cache_filename): print(f'running optimizations and storing to {cache_filename} ({nrun} runs of {epoch} epochs)') res = [] for _i, Tf in enumerate(Ts): res.append([pm_sa.search(scen.drone, scen.targets, epochs=epoch, debug=True, Tf=Tf, display=0, use_native=True) for _nr in range(nrun)]) _print_summary(_i, [_r[0].flight_duration() for _r in res[-1]]) np.savez(cache_filename, res=res)#, allow_pickle=True) else: print(f'loading optimization results from {cache_filename}') _d = np.load(cache_filename, allow_pickle=True) res = _d['res'] costs_by_runs = [[_l[0].flight_duration() for _l in _r] for _r in res ] fig = plt.figure(constrained_layout=True, figsize=[10.24, 5.12])#, tight_layout=True) fig.canvas.set_window_title(filename) gs = fig.add_gridspec(max(3, len(Ts)), 3) ax1 = fig.add_subplot(gs[0, :-1]) ax2 = fig.add_subplot(gs[1, :-1], sharex=ax1) ax3 = fig.add_subplot(gs[2, :-1], sharex=ax1) axes_chrono = [fig.add_subplot(gs[0,-1])] for _i in range(1, len(Ts)): axes_chrono.append(fig.add_subplot(gs[_i,-1], sharex=axes_chrono[0], sharey=axes_chrono[0])) colors_by_cases = [] _start = 0#int(9./10*epoch) for k, (Tf, _res) in enumerate(zip(Ts, res)): for _nr, (best_drone, best_seq, all_durs, kept_durs, Paccept, max_dur) in enumerate(_res): if _nr==0: _l = ax1.plot(kept_durs[_start:], label=f'{k}', alpha=0.6) colors_by_cases.append(_l[0].get_color()) ax1.plot(max_dur[_start:], color='black', alpha=0.4) ax3.plot([Ts[k](i) for i in range(_start, epoch)], label=f'{k}') else: ax1.plot(kept_durs[_start:], color=colors_by_cases[-1], alpha=0.6) ax1.plot(max_dur[_start:], color='black', alpha=0.4) ax2.plot(Paccept[_start:], color=colors_by_cases[-1], alpha=0.4)#, label=f'{k}') #pdb.set_trace() ylim = (0, 200) pmu.decorate(ax1, 'Cost', ylab='s', legend=True, ylim=ylim) pmu.decorate(ax2, 'Paccept')#, legend=True) pmu.decorate(ax3, 'Temperature', xlab='episode', ylab='s', legend=True) #plt.figure() #fig = plt.gcf(); fig.canvas.set_window_title(filename) #axes = fig.subplots(len(Ts),1, sharex=True, sharey=True, squeeze=False) for _i, (_c, _ax, _co) in enumerate(zip(costs_by_runs, axes_chrono, colors_by_cases)): _ax.hist(_c, alpha=0.6, color=_co) pmu.decorate(_ax, f'Final cost case {_i}', xlab='time in s')