Skip to content

Instantly share code, notes, and snippets.

@freestok
Last active August 10, 2020 15:06
Show Gist options
  • Save freestok/cdd70df1da63e5b7c48ac74c2a1ff77d to your computer and use it in GitHub Desktop.
Save freestok/cdd70df1da63e5b7c48ac74c2a1ff77d to your computer and use it in GitHub Desktop.
## credit to snake_charmer on StackOverflow for animation help https://stackoverflow.com/a/28015795
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.image as mgimg
from matplotlib import animation
def rando(nemo):
couples = math.floor(nemo/2) # get number of couples, round down
for coup in range(couples):
if np.random.random() >= .5:
# to us a nematode is given
nemo += 1
return nemo
def nematode_maker(days):
nematodes = 2
for i in range(days):
nematodes = rando(nematodes)
return nematodes
def simulation_percentages(sim, day):
plt.style.use('ggplot')
unique = list(set(sim))
# get percentages of nematode counts
sims = [(sim.count(i)/len(sim)) * 100 for i in unique]
x_pos = [i+2 for i, _ in enumerate(unique)] # nematode count starts at 2
plt.plot(x_pos,sims,color='green')
plt.xlabel('Nematodes')
plt.title(f'Chance of nematode count - Day {day+1}')
plt.savefig(f'nematode_{day+1}.png')
plt.show()
def init():
imobj.set_data(np.zeros((100, 100)))
return imobj,
def animate(i):
fname = f"nematode_{i+1}.png"
img = mgimg.imread(fname)[-1::-1]
imobj.set_data(img)
return imobj,
# distribution doesn't change all the much after this day
max_day = 17
simulations_count = 1000000
# start at day 4
for day in range(3,max_day):
simulation_percentages([nematode_maker(day) for i in range(simulations_count)],day)
fig = plt.figure()
ax = plt.gca()
imobj = ax.imshow( np.zeros((100, 100)), origin='lower', alpha=1.0, zorder=1, aspect=1 )
anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = True,
frames=range(3,max_day), interval=1000, blit=True, repeat_delay=1000)
anim.save('animation.mp4',dpi=300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment