Carnivores and Herbivores
Biodiversity: Current 0 Max 0
import matplotlib.pyplot as plt
import numpy as np
from pyodide import create_proxy, create_once_callable
from js import alert, setInterval, setTimeout, clearInterval
R_h_input = document.querySelector("#R_h")
R_c_input = document.querySelector("#R_c")
button = document.querySelector("#button1")
Herbivores = Carnivores = []
current_score = 0
max_score = 0
def plotSin():
plt.style.use('_mpl-gallery')
# make data
x = np.linspace(0, 10, 100)
y = 4 + 1 * np.sin(2 * x)
x2 = np.linspace(0, 10, 25)
y2 = 4 + 1 * np.sin(2 * x2)
# plot
fig, ax = plt.subplots()
ax.plot(x2, y2 + 2.5, 'x', markeredgewidth=2)
ax.plot(x, y, linewidth=2.0)
ax.plot(x2, y2 - 2.5, 'o-', linewidth=2)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 8), yticks=np.arange(1, 8))
Element("plot").write(fig)
def plotPop():
global Herbivores
global Carnivores
global current_score
global max_score
R_h = float(R_h_input.value)
R_c = float(R_c_input.value)
if len(Herbivores)==0:
Herbivores , Carnivores = population(R_h,R_c)
else:
Herbivores.pop(0)
Carnivores.pop(0)
H_nxt = H_next(Herbivores[-1], Carnivores[-1], R_h)
C_nxt = C_next(Herbivores[-1], Carnivores[-1], R_c)
Herbivores.append(H_nxt)
Carnivores.append(C_nxt)
# plot
fig, ax = plt.subplots()
t = range(len(Herbivores))
ax.plot(t, Herbivores, linewidth=2.0)
ax.plot(t, Carnivores, linewidth=2.0)
ax.set(xlim=(0, len(Herbivores)),
ylim=(0, 1))
current_score = round(10*(Herbivores[-1]+Carnivores[-1])/2 , 1)
if current_score > max_score:
max_score = current_score
score_txt = "Biodiversity: Current "+str(current_score)+" Max "+str(max_score)
Element("score").write(score_txt)
Element("plot").write(fig)
def H_next(H, C, R_h):
result = R_h*H*(1-H)/(1+C)
if result > 1:
return 1
elif result < 0:
return 0
else:
return result
def C_next(H, C, R_c):
result = R_c*C*(1-C)*(1+H)
if result > 1:
return 1
elif result < 0:
return 0
else:
return result
def population(R_h,R_c):
Herbivores = [0.8]
Carnivores = [0.1]
H = 0.8
C = 0.1
generation = 0
while generation < 40:
H_nxt = H_next(H, C, R_h)
C_nxt = C_next(H, C, R_c)
Herbivores.append(H_nxt)
Carnivores.append(C_nxt)
H = H_nxt
C = C_nxt
generation = generation+1
return (Herbivores, Carnivores)
def startPlot(event):
interval_id = setInterval(create_proxy(plotPop), 1000)
_ = setTimeout(
create_once_callable(
lambda: clearInterval(interval_id)
),
1000000
)
button = document.querySelector("#button1")
button.addEventListener("click", create_proxy(startPlot))