Fixation in population with weighted choices using Python

Question:

I’m trying to do a simulation to see how quickly a population fixates. The population consists of 1s (or p) and 0s (or q) while each individual has 2 elements (either 1-1, 1-0, or 0-0).

N is population and since each member of the population has 2 elements, the population pool will be 2*N (in this case 20)

initial frequency of the 1s is 0.1 and by default, q is 1 – 0.1 = 0.9

So the initial population is [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for the next population, i’m randomly choosing (weighted choice) based on the frequencies (p_freq and q_freq) and iterating through this until the population fixates to either all 1s or all 0s. Once it fixates, I’m trying to record the generation in which it fixates in either the p_fix or q_fix lists

So I’ve gotten this to work for one simulation, but i’m trying to get it to work for n= 100 simulations and I cant figure out how to structure it to get the loop to keep going to fill in the p_fix and q_fix lists correctly

#!/usr/bin/env python2.7
import random

N= 10
n= 100
p_freq= 0.1
q_freq= 1 - p_freq

simulation= 0
p_fix= []
q_fix= []

for sim in range(n):
    generation= 0
    #Current population
    p_alleles= int(p_freq * 2*N)*[1]
    q_alleles= int(q_freq * 2*N)*[0]
    population= p_alleles + q_alleles
    while (sum(population) != 2*N) and (sum(population) != 0):
        #Checking current population for fixation

        #Next generation
        next_population= []
        for i in range(2*N): next_population.append(random.choice(population))

        #Resetting parameters

        p_freq= float(sum(next_population))/(2*N)
        q_freq= 1 - p_freq
        population= next_population

        #Counts
        generation += 1
    if sum(population) == 2*N: 
        p_fix.append(generation)
    if sum(population) == 0: 
        q_fix.append(generation)
    simulation += 1

my results when I print out p_fix and q_fix:

p []
q [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

it shoudln’t be the 0th generation for all simulations after the first simulation. it does make sense, however, that the population is fixing to q because 90% of the original population was q (i.e. 0s). the frequencies change for each population (which is why i reset them) and that leads to fixation. Population size stays the same.

How can I get this to run for multiple simulations?

Asked By: O.rka

||

Answers:

Your issue is that you’re not resetting p_freq= 0.1, and q_freq= 1 - p_freq after each simulation. You need to reset them in your: for sim in range(n): loop (otherwise they retain the value from the last sim).

Answered By: Gerrat