Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pep8ify examples #3425

Merged
merged 21 commits into from Sep 9, 2014
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -34,6 +34,7 @@ script:
# Generate the font caches in a single process before starting the
# multiple processes
- python -c "from matplotlib import font_manager"
- if [[ $BUILD_DOCS == false ]]; then export MPL_REPO_DIR=$PWD; fi # pep8-conformance test of the examples
- if [[ $BUILD_DOCS == false ]]; then mkdir ../tmp_test_dir; fi
- if [[ $BUILD_DOCS == false ]]; then cd ../tmp_test_dir; fi
- if [[ $BUILD_DOCS == false ]]; then python ../matplotlib/tests.py -sv --processes=8 --process-timeout=300 $TEST_ARGS; fi
Expand Down
9 changes: 6 additions & 3 deletions examples/animation/animate_decay.py
Expand Up @@ -2,11 +2,12 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def data_gen():
t = data_gen.t
cnt = 0
while cnt < 1000:
cnt+=1
cnt += 1
t += 0.05
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
data_gen.t = 0
Expand All @@ -17,9 +18,11 @@ def data_gen():
ax.set_xlim(0, 5)
ax.grid()
xdata, ydata = [], []


def run(data):
# update the data
t,y = data
t, y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
Expand All @@ -32,5 +35,5 @@ def run(data):
return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
repeat=False)
repeat=False)
plt.show()
7 changes: 4 additions & 3 deletions examples/animation/basic_example.py
Expand Up @@ -2,8 +2,9 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def update_line(num, data, line):
line.set_data(data[...,:num])
line.set_data(data[..., :num])
return line,

fig1 = plt.figure()
Expand All @@ -15,7 +16,7 @@ def update_line(num, data, line):
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
interval=50, blit=True)
#line_ani.save('lines.mp4')

fig2 = plt.figure()
Expand All @@ -28,7 +29,7 @@ def update_line(num, data, line):
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
blit=True)
#im_ani.save('im.mp4', metadata={'artist':'Guido'})

plt.show()
7 changes: 4 additions & 3 deletions examples/animation/basic_example_writer.py
Expand Up @@ -7,8 +7,9 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def update_line(num, data, line):
line.set_data(data[...,:num])
line.set_data(data[..., :num])
return line,

# Set up formatting for the movie files
Expand All @@ -25,7 +26,7 @@ def update_line(num, data, line):
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and yet, here is an example that goes ahead and "saves" an animation... wtf?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this a problem? The examples are not run by travis-ci, are they?


fig2 = plt.figure()
Expand All @@ -38,5 +39,5 @@ def update_line(num, data, line):
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
blit=True)
im_ani.save('im.mp4', writer=writer)
3 changes: 2 additions & 1 deletion examples/animation/bayes_update.py
Expand Up @@ -4,6 +4,7 @@
import scipy.stats as ss
from matplotlib.animation import FuncAnimation


class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
Expand Down Expand Up @@ -43,5 +44,5 @@ def __call__(self, i):
ax = fig.add_subplot(1, 1, 1)
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
interval=100, blit=True)
interval=100, blit=True)
plt.show()
31 changes: 16 additions & 15 deletions examples/animation/double_pendulum_animated.py
Expand Up @@ -7,11 +7,11 @@
import scipy.integrate as integrate
import matplotlib.animation as animation

G = 9.8 # acceleration due to gravity, in m/s^2
L1 = 1.0 # length of pendulum 1 in m
L2 = 1.0 # length of pendulum 2 in m
M1 = 1.0 # mass of pendulum 1 in kg
M2 = 1.0 # mass of pendulum 2 in kg
G = 9.8 # acceleration due to gravity, in m/s^2
L1 = 1.0 # length of pendulum 1 in m
L2 = 1.0 # length of pendulum 2 in m
M1 = 1.0 # mass of pendulum 1 in kg
M2 = 1.0 # mass of pendulum 2 in kg


def derivs(state, t):
Expand All @@ -22,7 +22,8 @@ def derivs(state, t):
del_ = state[2]-state[0]
den1 = (M1+M2)*L1 - M2*L1*cos(del_)*cos(del_)
dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_)
+ M2*G*sin(state[2])*cos(del_) + M2*L2*state[3]*state[3]*sin(del_)
+ M2*G*sin(state[2])*cos(del_)
+ M2*L2*state[3]*state[3]*sin(del_)
- (M1+M2)*G*sin(state[0]))/den1

dydx[2] = state[3]
Expand All @@ -46,19 +47,17 @@ def derivs(state, t):
th2 = -10.0
w2 = 0.0

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this removed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unused var

rad = pi/180

# initial state
state = np.array([th1, w1, th2, w2])*pi/180.
state = np.radians([th1, w1, th2, w2])

# integrate your ODE using scipy.integrate.
y = integrate.odeint(derivs, state, t)

x1 = L1*sin(y[:,0])
y1 = -L1*cos(y[:,0])
x1 = L1*sin(y[:, 0])
y1 = -L1*cos(y[:, 0])

x2 = L2*sin(y[:,2]) + x1
y2 = -L2*cos(y[:,2]) + y1
x2 = L2*sin(y[:, 2]) + x1
y2 = -L2*cos(y[:, 2]) + y1

fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
Expand All @@ -68,21 +67,23 @@ def derivs(state, t):
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)


def init():
line.set_data([], [])
time_text.set_text('')
return line, time_text


def animate(i):
thisx = [0, x1[i], x2[i]]
thisy = [0, y1[i], y2[i]]

line.set_data(thisx, thisy)
time_text.set_text(time_template%(i*dt))
time_text.set_text(time_template % (i*dt))
return line, time_text

ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),
interval=25, blit=True, init_func=init)
interval=25, blit=True, init_func=init)

#ani.save('double_pendulum.mp4', fps=15)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and here is a commented out save call that didn't get a space. Seems to me like whatever tool was used wasn't consistent (but I prefer this style)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be a bug in autopep8. The pep8 tool still detects the E265 block comment should start with '# error on this line.

edit:
This was done on purpose:
from the autopep8 docs

E265, which refers to spacing after comment hash, is ignored if the comment looks like code. autopep8 avoids modifying these since they are not real comments. If you really want to get rid of the pep8 warning, consider just removing the commented-out code. (This can be automated via eradicate.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this does not conform to pep8 (http://legacy.python.org/dev/peps/pep-0008/#block-comments) but this is not a problem since we ignore E265.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have some issues with the comment related white-space rules #2930 ....

plt.show()
6 changes: 4 additions & 2 deletions examples/animation/dynamic_image.py
Expand Up @@ -8,6 +8,7 @@

fig = plt.figure()


def f(x, y):
return np.sin(x) + np.cos(y)

Expand All @@ -16,11 +17,12 @@ def f(x, y):

im = plt.imshow(f(x, y), cmap=plt.get_cmap('jet'))


def updatefig(*args):
global x,y
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x,y))
im.set_array(f(x, y))
return im,

ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
Expand Down
3 changes: 2 additions & 1 deletion examples/animation/dynamic_image2.py
Expand Up @@ -8,6 +8,7 @@

fig = plt.figure()


def f(x, y):
return np.sin(x) + np.cos(y)

Expand All @@ -24,7 +25,7 @@ def f(x, y):
ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
repeat_delay=1000)
repeat_delay=1000)

#ani.save('dynamic_images.mp4')

Expand Down
26 changes: 14 additions & 12 deletions examples/animation/histogram.py
Expand Up @@ -28,34 +28,36 @@
# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
# CLOSEPOLY; the vert for the closepoly is ignored but we still need
# it to keep the codes aligned with the vertices
nverts = nrects*(1+3+1)
nverts = nrects*(1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5,0] = left
verts[0::5,1] = bottom
verts[1::5,0] = left
verts[1::5,1] = top
verts[2::5,0] = right
verts[2::5,1] = top
verts[3::5,0] = right
verts[3::5,1] = bottom
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom

barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())


def animate(i):
# simulate new data coming in
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top = bottom + n
verts[1::5,1] = top
verts[2::5,1] = top
verts[1::5, 1] = top
verts[2::5, 1] = top

ani = animation.FuncAnimation(fig, animate, 100, repeat=False)
plt.show()
5 changes: 2 additions & 3 deletions examples/animation/moviewriter.py
Expand Up @@ -12,7 +12,7 @@

FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib',
comment='Movie support!')
comment='Movie support!')
writer = FFMpegWriter(fps=15, metadata=metadata)

fig = plt.figure()
Expand All @@ -21,12 +21,11 @@
plt.xlim(-5, 5)
plt.ylim(-5, 5)

x0,y0 = 0, 0
x0, y0 = 0, 0

with writer.saving(fig, "writer_test.mp4", 100):
for i in range(100):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()

16 changes: 8 additions & 8 deletions examples/animation/rain.py
Expand Up @@ -8,14 +8,14 @@
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import FuncAnimation


# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7,7))
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])

# Create rain data
n_drops = 50
Expand All @@ -31,7 +31,7 @@

# Construct the scatter which we will update during animation
# as the raindrops develop.
scat = ax.scatter(rain_drops['position'][:,0], rain_drops['position'][:,1],
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')

Expand All @@ -42,7 +42,7 @@ def update(frame_number):

# Make all colors more transparent as time progresses.
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:,3] = np.clip(rain_drops['color'][:,3], 0, 1)
rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)

# Make all circles bigger.
rain_drops['size'] += rain_drops['growth']
Expand All @@ -58,7 +58,7 @@ def update(frame_number):
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])


# Construct the animation, using the update function as the animation
# director.
Expand Down
5 changes: 4 additions & 1 deletion examples/animation/random_data.py
Expand Up @@ -6,12 +6,15 @@
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)


def update(data):
line.set_ydata(data)
return line,


def data_gen():
while True: yield np.random.rand(10)
while True:
yield np.random.rand(10)

ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()