|
| 1 | +import matplotlib.tri as mtri |
| 2 | +import numpy as np |
| 3 | +from matplotlib import animation |
| 4 | +from matplotlib import pyplot as plt |
| 5 | +from matplotlib.animation import FFMpegWriter |
| 6 | +from tqdm.auto import tqdm |
| 7 | + |
| 8 | +import adaptive |
| 9 | + |
| 10 | + |
| 11 | +def learner_till(till, learner, data): |
| 12 | + new_learner = adaptive.Learner2D(None, bounds=learner.bounds) |
| 13 | + new_learner.data = {k: v for k, v in data[:till]} |
| 14 | + for x, y in learner._bounds_points: |
| 15 | + # always include the bounds |
| 16 | + new_learner.tell((x, y), learner.data[x, y]) |
| 17 | + return new_learner |
| 18 | + |
| 19 | + |
| 20 | +def plot_tri(learner, ax): |
| 21 | + tri = learner.ip().tri |
| 22 | + triang = mtri.Triangulation(*tri.points.T, triangles=tri.vertices) |
| 23 | + return ax.triplot(triang, c="k", lw=0.8, alpha=0.8) |
| 24 | + |
| 25 | + |
| 26 | +def get_new_artists(npoints, learner, data): |
| 27 | + new_learner = learner_till(npoints, learner, data) |
| 28 | + line1, line2 = plot_tri(new_learner, ax) |
| 29 | + data = np.rot90(new_learner.interpolated_on_grid()[-1]) |
| 30 | + im = ax.imshow(data, extent=(-0.5, 0.5, -0.5, 0.5), cmap="viridis") |
| 31 | + return im, line1, line2 |
| 32 | + |
| 33 | + |
| 34 | +def create_and_run_learner(): |
| 35 | + def ring(xy): |
| 36 | + import numpy as np |
| 37 | + |
| 38 | + x, y = xy |
| 39 | + a = 0.2 |
| 40 | + return x + np.exp(-((x ** 2 + y ** 2 - 0.75 ** 2) ** 2) / a ** 4) |
| 41 | + |
| 42 | + learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)]) |
| 43 | + adaptive.runner.simple(learner, goal=lambda l: l.loss() < 0.005) |
| 44 | + return learner |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + learner = create_and_run_learner() |
| 49 | + |
| 50 | + data = list(learner.data.items()) |
| 51 | + |
| 52 | + fig, ax = plt.subplots(figsize=(5, 5)) |
| 53 | + fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) |
| 54 | + ax.set_xticks([]) |
| 55 | + ax.set_yticks([]) |
| 56 | + |
| 57 | + nseconds = 15 |
| 58 | + npoints = (len(data) * np.linspace(0, 1, 24 * nseconds) ** 2).astype(int) |
| 59 | + |
| 60 | + artists = [get_new_artists(n, learner, data) for n in tqdm(npoints)] |
| 61 | + |
| 62 | + ani = animation.ArtistAnimation(fig, artists, blit=True) |
| 63 | + ani.save("logo.mp4", writer=FFMpegWriter(fps=24)) |
0 commit comments