Appendix: Logistic Growth (Details and Hints)

Logistic Population Growth in Python

Getting Rid of Globals

Python models often avoid introducing the global variables that are natural in NetLogo. One common approach to this is to introduce a World class that is able to initialize and run the simulation. This World class should be intitialized with the maximal growth rate (g), the initial population (pop, and the carrying capacity (pbar). Make sure that it accumulates a history at each step.

class World(object):
    def __init__(self, prms):
        self.g = prms['g']
        self.pop0 = prms['pop']  #initial population
        self.pbar = prms['pbar'] #reference population
    def setup(self):
        self.relpop = self.pop0 / self.pbar
        self.nextLogistic = lambda x: x + self.g * x * (1 - x)
        self.trajectory = [self.pop0]
        self.ticks = 0
    def step(self):
        self.relpop = self.nextLogistic(self.relpop)
        self.ticks += 1
    def recordStep(self):
        newpop = self.pbar * self.relpop  #population
        self.trajectory.append(newpop)    #data collection
    def runsim(self):
        self.setup()
        for _ in range(50):
            self.step()                              #simulation step
            self.trajectory.append(self.pbar * self.relpop) #data collection

Set up and run a simulation as follows.

world = World(g=0.03, pop=7.75, pbar=11)
world.runsim()

Many Python packages can produce visualizations of the results. For two-dimensional plots, matplotlib is an excellent and popular choice.

from matplotlib import pyplot as plt
plt.plot(world.history)
plt.show()

References


version:

2024-05-15