mirror of
https://github.com/wassname/viz_torch_optim.git
synced 2026-08-04 13:23:42 +08:00
411 KiB
411 KiB
In [432]:
%pylab inlinePopulating the interactive namespace from numpy and matplotlib
/home/isisilon/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/IPython/core/magics/pylab.py:160: UserWarning: pylab import has clobbered these variables: ['np', 'f'] `%matplotlib` prevents importing * from pylab and numpy "\n`%matplotlib` prevents importing * from pylab and numpy"
In [433]:
import torch
from torch.autograd import VariableIn [434]:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LogNorm
from matplotlib import animation
from IPython.display import HTML
from collections import defaultdict
from itertools import zip_longest
from functools import partialIn [ ]:
In [643]:
from torch.optim import SGD, Adadelta, Adam
import torch.optim as optim
In [644]:
def test_f(constructor, steps=150, x0=[-4,-1], solution=[-2,0]):
state = {}
# start
params = Variable(torch.Tensor(x0), requires_grad=True)
optimizer = constructor([params])
solution = torch.Tensor(solution)
initial_dist = params.data.dist(solution)
def eval():
optimizer.zero_grad()
loss = f(params)
loss.backward()
# loss.backward() will give **slightly** different
# gradients, than drosenbtock, because of a different ordering
# of floating point operations. In most cases it doesn't matter,
# but some optimizers are so sensitive that they can temporarily
# diverge up to 1e-4, just to converge again. This makes the
# comparison more stable.
params.grad.data.copy_(df(params.data))
return loss
# print(params.data.dist(solution), initial_dist)
# print(params.data, params_t)
data=[]
dist=[]
for i in range(steps):
optimizer.step(eval)
dist.append(params.data.dist(solution)) # loss
data.append(params.data.numpy().copy())
return np.array(data), np.array(dist)In [650]:
"""Valley"""
def beales(x, y):
"""Beales function, like a valley"""
return (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2# + noise(x,y)
def dbeales(x, y):
pass # TODO
# return (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2# + noise(x,y)
f = beales
df = dbeales
minima = np.array([3., .5])In [942]:
"""A hilly landscape"""
def madsen(tensor):
x1, x2 = tensor
# x1 = torch.Tensor(x1)
# x2 = torch.Tensor(x2)
"""Madsen function (1981)."""
r = x1**2 + x2**2 + x1 * x2 +\
torch.sin(x1) +\
torch.cos(x2) #+ np.abs(noise(x1,x2))
return r.numpy()
def dmadsen(tensor):
x1, x2 = tensor
# x1 = torch.Tensor(x1)
# x2 = torch.Tensor(x2)
return 2*x1 +x2 + 2*x2+x1 + torch.cos(x1)-torch.sin(x2)
f = madsen
df = dmadsen
minima = np.array([-0.39999999999999591, 0.20000000000000462])
# zmax = 1e1In [943]:
"""Banana shaped"""
def rosenbrock(tensor):
x, y = tensor
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
def drosenbrock(tensor):
x, y = tensor
return torch.Tensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2)))
x0 = [-3,-4] # start
f = rosenbrock
df = drosenbrock
minima = np.array([1,1])In [944]:
# define boundaries
xmin, xmax, xstep = -5, 5, .05
ymin, ymax, ystep = -5, 5, .05
# x0 = np.array([3., 4.])
# and x, y, z
x, y = np.meshgrid(np.arange(xmin, xmax + xstep, xstep), np.arange(ymin, ymax + ystep, ystep))
z = f([x, y])In [945]:
# define minima
minima_ = minima.reshape(-1, 1)
minima_
z_min = f(minima)
_x0 = np.array([x0]).TIn [946]:
steps=3000
lr=1e-4In [947]:
constructors = dict(
Adam = lambda params: optim.Adam(params, lr=lr),
# lambda params: optim.Adam(params, lr=lr, weight_decay=1e-2),
Adadelta = lambda params: optim.Adadelta(params),
Adagrad = lambda params: optim.Adagrad(params, lr=lr),
Adamax = lambda params: optim.Adamax(params, lr=lr),
RMSprop = lambda params: optim.RMSprop(params, lr=lr),
# ASGD = lambda params: optim.ASGD(params, lr=lr),
# Rprop = lambda params: optim.Rprop(params, lr=lr),
# LBFGS = lambda params: optim.LBFGS(params),
SGD= lambda params: optim.SGD(params, lr=lr),
momentum = lambda params: optim.SGD(params, lr=lr, momentum=0.5),
nesterov = lambda params: optim.SGD(params, lr=lr, momentum=0.5, nesterov=True),
# decay = lambda params: optim.SGD(params, lr=lr, weight_decay=1e-4),
)In [948]:
optim.SGDOut [948]:
torch.optim.sgd.SGD
In [ ]:
results = {}
distance = {}
for name, constructor in constructors.items():
data, dist = test_f(constructor, x0=x0, steps=steps)
results[name] = data
distance[name] = distIn [ ]:
# calc paths and elevation
methods = constructors.keys()
paths = np.array([path.T for path in results.values()]) # should be (2,N) each
zpaths = np.array([[f(p) for p in path.T] for path in paths])
paths.shape, zpaths.shapeIn [ ]:
In [ ]:
# DEBUG: check z's
for i, name in enumerate(results):
zmax = zpaths[i][np.isfinite(zpaths[i])].max()
print(name, zmax, np.isfinite(zmax).all())In [ ]:
for i, name in enumerate(results):
plt.plot(np.abs(zpaths[i]-z_min), label=name)
plt.legend()
plt.title('loss (mae)')In [ ]:
for name in distance:
plt.plot(distance[name], label=name)
plt.legend()
plt.title('distance from ideal minima')In [ ]:
# quick plot to let you debug your steps and learning rate
ax = plt.gca()
for name in results:
plt.scatter(*results[name].T, label=name, s=1)
plt.legend()
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax)
zmax=int(np.log(z.max()))/2
ax.contour(x, y, z, levels=np.logspace(0, zmax, zmax*7), norm=LogNorm(), cmap=plt.cm.jet, alpha=0.15)
ax.plot(*minima_, 'r*', markersize=10)
ax.plot(*x0, 'r+', markersize=10)
plt.title('debug: paths')
plt.show()In [ ]:
fig = plt.figure(figsize=(8, 5))
ax = plt.axes(projection='3d', elev=50, azim=65)
ax.plot_surface(x, y, z, norm=LogNorm(), rstride=1, cstride=1, edgecolor='none', alpha=.25, cmap=plt.cm.jet)
ax.plot(*minima_, f(minima_), 'r*', markersize=10)
ax.plot(*_x0, f(_x0), 'r+', markersize=10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
# anim = TrajectoryAnimation3D(*paths, zpaths=zpaths, labels=methods, ax=ax)
# quick plot to let you debug your steps and learning rate
ax = plt.gca()
for i, name in enumerate(results):
ax.scatter3D(*results[name].T, zpaths[i], label=name, s=1)
plt.legend()
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax)
ax.legend(loc='best')In [559]:
class TrajectoryAnimation(animation.FuncAnimation):
def __init__(self, *paths, labels=[], fig=None, ax=None, frames=None,
interval=60, repeat_delay=5, blit=True, **kwargs):
if fig is None:
if ax is None:
fig, ax = plt.subplots()
else:
fig = ax.get_figure()
else:
if ax is None:
ax = fig.gca()
self.fig = fig
self.ax = ax
self.paths = paths
if frames is None:
frames = max(path.shape[1] for path in paths)
self.lines = [ax.plot([], [], label=label, lw=2)[0]
for _, label in zip_longest(paths, labels)]
self.points = [ax.plot([], [], 'o', color=line.get_color())[0]
for line in self.lines]
super(TrajectoryAnimation, self).__init__(fig, self.animate, init_func=self.init_anim,
frames=frames, interval=interval, blit=blit,
repeat_delay=repeat_delay, **kwargs)
def init_anim(self):
for line, point in zip(self.lines, self.points):
line.set_data([], [])
point.set_data([], [])
return self.lines + self.points
def animate(self, i):
for line, point, path in zip(self.lines, self.points, self.paths):
line.set_data(*path[::,:i])
point.set_data(*path[::,i-1:i])
return self.lines + self.pointsIn [560]:
class TrajectoryAnimation3D(animation.FuncAnimation):
def __init__(self, *paths, zpaths, labels=[], fig=None, ax=None, frames=None,
interval=60, repeat_delay=5, blit=True, **kwargs):
if fig is None:
if ax is None:
fig, ax = plt.subplots()
else:
fig = ax.get_figure()
else:
if ax is None:
ax = fig.gca()
self.fig = fig
self.ax = ax
self.paths = paths
self.zpaths = zpaths
if frames is None:
frames = max(path.shape[1] for path in paths)
self.lines = [ax.plot([], [], [], label=label, lw=2)[0]
for _, label in zip_longest(paths, labels)]
super(TrajectoryAnimation3D, self).__init__(fig, self.animate, init_func=self.init_anim,
frames=frames, interval=interval, blit=blit,
repeat_delay=repeat_delay, **kwargs)
def init_anim(self):
for line in self.lines:
line.set_data([], [])
line.set_3d_properties([])
return self.lines
def animate(self, i):
for line, path, zpath in zip(self.lines, self.paths, self.zpaths):
line.set_data(*path[::,:i])
line.set_3d_properties(zpath[:i])
return self.linesIn [569]:
fig, ax = plt.subplots(figsize=(10, 6))
ax.contour(x, y, z, levels=np.logspace(0, 5, 35), norm=LogNorm(), cmap=plt.cm.jet, alpha=0.5)
ax.plot(*minima_, 'r*', markersize=10)
ax.plot(*x0, 'r+', markersize=10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
anim = TrajectoryAnimation(*paths, labels=methods, ax=ax)
ax.legend(loc='upper left')Out [569]:
<matplotlib.legend.Legend at 0x7f72ef238f60>
In [564]:
# anim.to_html5_video()
save_file = '{name:}.m4v'.format(name=f.__name__)
anim.save(save_file)
# display
html="""<video {options}>
<source type="video/mp4" src="{video}">
Your browser does not support the video tag.
</video>""".format(options=' '.join(['controls', 'autoplay']), video=save_file)
print(html)
HTML(html)Out [564]:
<video controls autoplay> <source type="video/mp4" src="rosenbrock.m4v"> Your browser does not support the video tag. </video>
In [583]:
In [590]:
fig = plt.figure(figsize=(8, 5))
ax = plt.axes(projection='3d', elev=50, azim=65)
ax.plot_surface(x, y, z, norm=LogNorm(), rstride=1, cstride=1, edgecolor='none', alpha=.8, cmap=plt.cm.jet)
ax.plot(*minima_, f(minima_), 'r*', markersize=10)
ax.plot(*_x0, f(_x0), 'r+', markersize=10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
anim = TrajectoryAnimation3D(*paths, zpaths=zpaths, labels=methods, ax=ax)
ax.legend(loc='bottom left')Out [590]:
<matplotlib.legend.Legend at 0x7f72f52d29e8>
In [591]:
# anim.to_html5_video()
save_file3d = save_file.replace('.m4v', '_3d.m4v')
anim.save(save_file3d)
# display
html="""<video {options}>
<source type="video/mp4" src="{video}">
Your browser does not support the video tag.
</video>""".format(options=' '.join(['controls', 'autoplay']), video=save_file3d)
print(html)
HTML(html)[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) [0;32m<ipython-input-591-5bdae6502204>[0m in [0;36m<module>[0;34m()[0m [1;32m 2[0m [0msave_file3d[0m [0;34m=[0m [0msave_file[0m[0;34m.[0m[0mreplace[0m[0;34m([0m[0;34m'.m4v'[0m[0;34m,[0m [0;34m'3d.m4v'[0m[0;34m)[0m[0;34m[0m[0m [1;32m 3[0m [0;34m[0m[0m [0;32m----> 4[0;31m [0manim[0m[0;34m.[0m[0msave[0m[0;34m([0m[0msave_file3d[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 5[0m [0;34m[0m[0m [1;32m 6[0m [0;31m# display[0m[0;34m[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/animation.py[0m in [0;36msave[0;34m(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs)[0m [1;32m 1060[0m [0;32mfor[0m [0manim[0m[0;34m,[0m [0md[0m [0;32min[0m [0mzip[0m[0;34m([0m[0mall_anim[0m[0;34m,[0m [0mdata[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [1;32m 1061[0m [0;31m# TODO: See if turning off blit is really necessary[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1062[0;31m [0manim[0m[0;34m.[0m[0m_draw_next_frame[0m[0;34m([0m[0md[0m[0;34m,[0m [0mblit[0m[0;34m=[0m[0;32mFalse[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 1063[0m [0mwriter[0m[0;34m.[0m[0mgrab_frame[0m[0;34m([0m[0;34m**[0m[0msavefig_kwargs[0m[0;34m)[0m[0;34m[0m[0m [1;32m 1064[0m [0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/animation.py[0m in [0;36m_draw_next_frame[0;34m(self, framedata, blit)[0m [1;32m 1098[0m [0mself[0m[0;34m.[0m[0m_pre_draw[0m[0;34m([0m[0mframedata[0m[0;34m,[0m [0mblit[0m[0;34m)[0m[0;34m[0m[0m [1;32m 1099[0m [0mself[0m[0;34m.[0m[0m_draw_frame[0m[0;34m([0m[0mframedata[0m[0;34m)[0m[0;34m[0m[0m [0;32m-> 1100[0;31m [0mself[0m[0;34m.[0m[0m_post_draw[0m[0;34m([0m[0mframedata[0m[0;34m,[0m [0mblit[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 1101[0m [0;34m[0m[0m [1;32m 1102[0m [0;32mdef[0m [0m_init_draw[0m[0;34m([0m[0mself[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/animation.py[0m in [0;36m_post_draw[0;34m(self, framedata, blit)[0m [1;32m 1123[0m [0mself[0m[0;34m.[0m[0m_blit_draw[0m[0;34m([0m[0mself[0m[0;34m.[0m[0m_drawn_artists[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0m_blit_cache[0m[0;34m)[0m[0;34m[0m[0m [1;32m 1124[0m [0;32melse[0m[0;34m:[0m[0;34m[0m[0m [0;32m-> 1125[0;31m [0mself[0m[0;34m.[0m[0m_fig[0m[0;34m.[0m[0mcanvas[0m[0;34m.[0m[0mdraw_idle[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 1126[0m [0;34m[0m[0m [1;32m 1127[0m [0;31m# The rest of the code in this class is to facilitate easy blitting[0m[0;34m[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/backend_bases.py[0m in [0;36mdraw_idle[0;34m(self, *args, **kwargs)[0m [1;32m 2038[0m [0;32mif[0m [0;32mnot[0m [0mself[0m[0;34m.[0m[0m_is_idle_drawing[0m[0;34m:[0m[0;34m[0m[0m [1;32m 2039[0m [0;32mwith[0m [0mself[0m[0;34m.[0m[0m_idle_draw_cntx[0m[0;34m([0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m-> 2040[0;31m [0mself[0m[0;34m.[0m[0mdraw[0m[0;34m([0m[0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 2041[0m [0;34m[0m[0m [1;32m 2042[0m [0;32mdef[0m [0mdraw_cursor[0m[0;34m([0m[0mself[0m[0;34m,[0m [0mevent[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py[0m in [0;36mdraw[0;34m(self)[0m [1;32m 462[0m [0;34m[0m[0m [1;32m 463[0m [0;32mtry[0m[0;34m:[0m[0;34m[0m[0m [0;32m--> 464[0;31m [0mself[0m[0;34m.[0m[0mfigure[0m[0;34m.[0m[0mdraw[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mrenderer[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 465[0m [0;32mfinally[0m[0;34m:[0m[0;34m[0m[0m [1;32m 466[0m [0mRendererAgg[0m[0;34m.[0m[0mlock[0m[0;34m.[0m[0mrelease[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/artist.py[0m in [0;36mdraw_wrapper[0;34m(artist, renderer, *args, **kwargs)[0m [1;32m 61[0m [0;32mdef[0m [0mdraw_wrapper[0m[0;34m([0m[0martist[0m[0;34m,[0m [0mrenderer[0m[0;34m,[0m [0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [1;32m 62[0m [0mbefore[0m[0;34m([0m[0martist[0m[0;34m,[0m [0mrenderer[0m[0;34m)[0m[0;34m[0m[0m [0;32m---> 63[0;31m [0mdraw[0m[0;34m([0m[0martist[0m[0;34m,[0m [0mrenderer[0m[0;34m,[0m [0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 64[0m [0mafter[0m[0;34m([0m[0martist[0m[0;34m,[0m [0mrenderer[0m[0;34m)[0m[0;34m[0m[0m [1;32m 65[0m [0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/figure.py[0m in [0;36mdraw[0;34m(self, renderer)[0m [1;32m 1142[0m [0;34m[0m[0m [1;32m 1143[0m mimage._draw_list_compositing_images( [0;32m-> 1144[0;31m renderer, self, dsu, self.suppressComposite) [0m[1;32m 1145[0m [0;34m[0m[0m [1;32m 1146[0m [0mrenderer[0m[0;34m.[0m[0mclose_group[0m[0;34m([0m[0;34m'figure'[0m[0;34m)[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/matplotlib/image.py[0m in [0;36m_draw_list_compositing_images[0;34m(renderer, parent, dsu, suppress_composite)[0m [1;32m 137[0m [0;32mif[0m [0mnot_composite[0m [0;32mor[0m [0;32mnot[0m [0mhas_images[0m[0;34m:[0m[0;34m[0m[0m [1;32m 138[0m [0;32mfor[0m [0mzorder[0m[0;34m,[0m [0ma[0m [0;32min[0m [0mdsu[0m[0;34m:[0m[0;34m[0m[0m [0;32m--> 139[0;31m [0ma[0m[0;34m.[0m[0mdraw[0m[0;34m([0m[0mrenderer[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 140[0m [0;32melse[0m[0;34m:[0m[0;34m[0m[0m [1;32m 141[0m [0;31m# Composite any adjacent images together[0m[0;34m[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py[0m in [0;36mdraw[0;34m(self, renderer)[0m [1;32m 269[0m [0;31m# Calculate projection of collections and zorder them[0m[0;34m[0m[0;34m[0m[0m [1;32m 270[0m zlist = [(col.do_3d_projection(renderer), col) \ [0;32m--> 271[0;31m for col in self.collections] [0m[1;32m 272[0m [0mzlist[0m[0;34m.[0m[0msort[0m[0;34m([0m[0mkey[0m[0;34m=[0m[0mitemgetter[0m[0;34m([0m[0;36m0[0m[0;34m)[0m[0;34m,[0m [0mreverse[0m[0;34m=[0m[0;32mTrue[0m[0;34m)[0m[0;34m[0m[0m [1;32m 273[0m [0;32mfor[0m [0mi[0m[0;34m,[0m [0;34m([0m[0mz[0m[0;34m,[0m [0mcol[0m[0;34m)[0m [0;32min[0m [0menumerate[0m[0;34m([0m[0mzlist[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py[0m in [0;36m<listcomp>[0;34m(.0)[0m [1;32m 269[0m [0;31m# Calculate projection of collections and zorder them[0m[0;34m[0m[0;34m[0m[0m [1;32m 270[0m zlist = [(col.do_3d_projection(renderer), col) \ [0;32m--> 271[0;31m for col in self.collections] [0m[1;32m 272[0m [0mzlist[0m[0;34m.[0m[0msort[0m[0;34m([0m[0mkey[0m[0;34m=[0m[0mitemgetter[0m[0;34m([0m[0;36m0[0m[0;34m)[0m[0;34m,[0m [0mreverse[0m[0;34m=[0m[0;32mTrue[0m[0;34m)[0m[0;34m[0m[0m [1;32m 273[0m [0;32mfor[0m [0mi[0m[0;34m,[0m [0;34m([0m[0mz[0m[0;34m,[0m [0mcol[0m[0;34m)[0m [0;32min[0m [0menumerate[0m[0;34m([0m[0mzlist[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py[0m in [0;36mdo_3d_projection[0;34m(self, renderer)[0m [1;32m 630[0m z_segments_2d = [(self._zsortfunc(zs), list(zip(xs, ys)), fc, ec, [1;32m 631[0m idx) for (xs, ys, zs), fc, ec, idx in [0;32m--> 632[0;31m zip(xyzlist, cface, cedge, indices)] [0m[1;32m 633[0m [0mz_segments_2d[0m[0;34m.[0m[0msort[0m[0;34m([0m[0mkey[0m[0;34m=[0m[0;32mlambda[0m [0mx[0m[0;34m:[0m [0mx[0m[0;34m[[0m[0;36m0[0m[0;34m][0m[0;34m,[0m [0mreverse[0m[0;34m=[0m[0;32mTrue[0m[0;34m)[0m[0;34m[0m[0m [1;32m 634[0m [0;32melse[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py[0m in [0;36m<listcomp>[0;34m(.0)[0m [1;32m 629[0m [0mindices[0m [0;34m=[0m [0mrange[0m[0;34m([0m[0mlen[0m[0;34m([0m[0mxyzlist[0m[0;34m)[0m[0;34m)[0m[0;34m[0m[0m [1;32m 630[0m z_segments_2d = [(self._zsortfunc(zs), list(zip(xs, ys)), fc, ec, [0;32m--> 631[0;31m idx) for (xs, ys, zs), fc, ec, idx in [0m[1;32m 632[0m zip(xyzlist, cface, cedge, indices)] [1;32m 633[0m [0mz_segments_2d[0m[0;34m.[0m[0msort[0m[0;34m([0m[0mkey[0m[0;34m=[0m[0;32mlambda[0m [0mx[0m[0;34m:[0m [0mx[0m[0;34m[[0m[0;36m0[0m[0;34m][0m[0;34m,[0m [0mreverse[0m[0;34m=[0m[0;32mTrue[0m[0;34m)[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/numpy/lib/function_base.py[0m in [0;36maverage[0;34m(a, axis, weights, returned)[0m [1;32m 1108[0m [0;34m[0m[0m [1;32m 1109[0m [0;32mif[0m [0mweights[0m [0;32mis[0m [0;32mNone[0m[0;34m:[0m[0;34m[0m[0m [0;32m-> 1110[0;31m [0mavg[0m [0;34m=[0m [0ma[0m[0;34m.[0m[0mmean[0m[0;34m([0m[0maxis[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 1111[0m [0mscl[0m [0;34m=[0m [0mavg[0m[0;34m.[0m[0mdtype[0m[0;34m.[0m[0mtype[0m[0;34m([0m[0ma[0m[0;34m.[0m[0msize[0m[0;34m/[0m[0mavg[0m[0;34m.[0m[0msize[0m[0;34m)[0m[0;34m[0m[0m [1;32m 1112[0m [0;32melse[0m[0;34m:[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/numpy/core/_methods.py[0m in [0;36m_mean[0;34m(a, axis, dtype, out, keepdims)[0m [1;32m 52[0m [0;34m[0m[0m [1;32m 53[0m [0;32mdef[0m [0m_mean[0m[0;34m([0m[0ma[0m[0;34m,[0m [0maxis[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m [0mdtype[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m [0mout[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m [0mkeepdims[0m[0;34m=[0m[0;32mFalse[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m [0;32m---> 54[0;31m [0marr[0m [0;34m=[0m [0masanyarray[0m[0;34m([0m[0ma[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 55[0m [0;34m[0m[0m [1;32m 56[0m [0mis_float16_result[0m [0;34m=[0m [0;32mFalse[0m[0;34m[0m[0m [0;32m~/.pyenv/versions/3.6.0/envs/jupyter3/lib/python3.6/site-packages/numpy/core/numeric.py[0m in [0;36masanyarray[0;34m(a, dtype, order)[0m [1;32m 581[0m [0;34m[0m[0m [1;32m 582[0m """ [0;32m--> 583[0;31m [0;32mreturn[0m [0marray[0m[0;34m([0m[0ma[0m[0;34m,[0m [0mdtype[0m[0;34m,[0m [0mcopy[0m[0;34m=[0m[0;32mFalse[0m[0;34m,[0m [0morder[0m[0;34m=[0m[0morder[0m[0;34m,[0m [0msubok[0m[0;34m=[0m[0;32mTrue[0m[0;34m)[0m[0;34m[0m[0m [0m[1;32m 584[0m [0;34m[0m[0m [1;32m 585[0m [0;34m[0m[0m [0;31mKeyboardInterrupt[0m:
In [ ]:
fig, ax = plt.subplots(figsize=(10, 6))
ax.contour(x, y, z, levels=np.logspace(0, 5, 35), norm=LogNorm(), cmap=plt.cm.jet, alpha=0.5)
ax.plot(*minima_, 'r*', markersize=10)
ax.plot(*x0, 'r+', markersize=10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
anim = TrajectoryAnimation(*paths, labels=methods, ax=ax)
ax.legend(loc='upper left')