help= "name of file to output selected locus information (default: (dir)/sel_loci.txt)" ) parser.add_argument( "--samples_file", "-e", help= "name of file to output information on samples (default=(dir)/samples.tsv)" ) args = parser.parse_args() import simuOpt import simuPOP as sim sim.setRNG(seed=args.seed) random.seed(args.seed) if args.outfile is not None: outfile = fileopt(args.outfile, "w") logfile = fileopt(args.logfile, "w") if args.selloci_file is None: args.selloci_file = os.path.join(os.path.dirname(args.treefile), "sel_loci.txt") selloci_file = args.selloci_file if args.samples_file is None: args.samples_file = os.path.join(os.path.dirname(args.treefile), "samples.tsv") samples_file = fileopt(args.samples_file, "w") # compute these here so they get recorded in the log
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim import random def simulate(): pop = sim.Population(1000, loci=10, infoFields='age') pop.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[0.5, 0.5]), sim.InitInfo(lambda: random.randint(0, 10), infoFields='age') ], matingScheme=sim.RandomMating(), finalOps=sim.Stat(alleleFreq=0), gen=100 ) return pop.dvars().alleleFreq[0][0] seed = sim.getRNG().seed() random.seed(seed) print('%.4f' % simulate()) # will yield different result print('%.4f' % simulate()) sim.setRNG(seed=seed) random.seed(seed) # will yield identical result because the same seeds are used print('%.4f' % simulate())
def simuAssortativeMatingWithFitness(e): ''' Accepts: e an Experiment object. Returns a dict containing the results from each gen of the simulation: gen generation number. A frequency of the A allele. a frequency of the a allele. AA frequency of AA individuals. Aa frequency of Aa individuals. aa frequency of aa individuals. deaf frequency of deaf individuals (incl adventitious). AA_size size of the AA subpopulation. Aa_size size of the Aa subpopulation. aa_size size of the aa subpopulation. deaf_size size of the deaf subpopulation (incl adventitious). homogamy calculated actual homogamy. F calculated inbreeding coefficient. Adopted from: http://simupop.sourceforge.net/Cookbook/AssortativeMating ''' sim.setRNG(random.seed(sim.getRNG().seed())) pop = sim.Population(e.constant_pop_size * 1000, loci=[1]) # These variables need to be set in order to be available to customChooser(). # There appears to be no way to directly pass variables to customChooser(). pop.dvars().constant_pop_size = e.constant_pop_size pop.dvars().a = e.a pop.dvars().aa_fitness = e.aa_fitness pop.dvars().aa_homogamy = e.aa_homogamy pop.dvars().deaf = e.deaf pop.dvars().adv_deaf_target = int( round((e.deaf - e.a**2) * e.constant_pop_size * 1000)) # These will hold the final data pop.dvars().headers = [] pop.dvars().row = [] pop.evolve( initOps= [sim.InitGenotype(freq=[1-e.a, e.a])], matingScheme = sim.HomoMating( chooser = sim.PyParentsChooser(customChooser), generator = sim.OffspringGenerator(sim.MendelianGenoTransmitter())), postOps = [sim.Stat(alleleFreq=[0], genoFreq=[0]), sim.PyExec(r"headers += ['gen','A', 'a',"\ "'AA', 'Aa', 'aa', 'deaf', 'AA_size', 'Aa_size', " \ "'aa_size', 'deaf_size', 'homogamy', 'F'] \n" \ "F = 1.0-((genoFreq[0][(0,1)]+genoFreq[0][(1,0)])/" # F \ "(2.0*alleleFreq[0][0]*alleleFreq[0][1])) "\ "if alleleFreq[0][0]*alleleFreq[0][1] > 0. "\ "else 0. \n" \ "deaf_size = min(genoNum[0][(1,1)] + adv_deaf_target, constant_pop_size*1000) \n"\ "row += [gen, " # generation \ "alleleFreq[0][0], " # A \ "alleleFreq[0][1], " # a \ "genoFreq[0][(0,0)]," # AA \ "genoFreq[0][(0,1)]+genoFreq[0][(1,0)], " # Aa \ "genoFreq[0][(1,1)], " # aa \ "deaf_size/(constant_pop_size*1000.), " # deaf \ "genoNum[0][(0,0)], " # AA_size \ "genoNum[0][(0,1)]+genoNum[0][(1,0)], " # Aa_size \ "genoNum[0][(1,1)], " # aa_size \ "deaf_size, " # deaf_size \ "homogamy, " # homogamy \ "F if F>0. else 0.]") # F \ ], gen = e.generations ) return {'headers': pop.dvars().headers, 'row': pop.dvars().row}
def simuAssortativeMatingWithFitness(constant_pop_size, a, aa_fitness, aa_homogamy, deafness_freq, generations): ''' Accepts: constant_pop_size population size, which remains constant throughout. a starting frequency of the a allele. aa_fitness _relative_ fitness of deaf (aa) individuals. aa_homogamy the percent of assortative mating between deaf individuals. deafness_freq overall frequency of deaf individuals at the time of reproductive age, including from causes other than connexin 26. generations number of generations. Returns a dict containing the results from each gen of the simulation: gen generation number. A frequency of the A allele. a frequency of the a allele. AA frequency of AA individuals. Aa frequency of Aa individuals. aa frequency of aa individuals. AA_size size of the AA subpopulation. Aa_size size of the Aa subpopulation. aa_size size of the aa subpopulation. F calculated inbreeding coefficient. num_deaf size of the deaf subpopulation (incl adventitious). homogamy calculated actual homogamy. Adopted from: http://simupop.sourceforge.net/Cookbook/AssortativeMating ''' sim.setRNG(random.seed(sim.getRNG().seed())) pop = sim.Population(constant_pop_size*1000, loci=[1]) pop.dvars().constant_pop_size = constant_pop_size pop.dvars().a = a pop.dvars().aa_fitness = aa_fitness pop.dvars().aa_homogamy = aa_homogamy pop.dvars().deafness_freq = deafness_freq pop.dvars().generations = generations pop.dvars().headers = [] pop.dvars().row = [] pop.evolve( initOps= [sim.InitSex(), # Assigns individuals randomly to be male or female. # This can result in slightly more males or females, # which can cause errors if the wrong mating scheme is # selected. sim.InitGenotype(freq=[1-a, a]) ], matingScheme = sim.HomoMating( chooser = sim.PyParentsChooser(customChooser), generator = sim.OffspringGenerator(sim.MendelianGenoTransmitter())), postOps = [sim.Stat(alleleFreq=[0], genoFreq=[0]), sim.PyExec(r"headers += ['gen','A', 'a',"\ "'AA', 'Aa', 'aa',"\ "'AA_size', 'Aa_size', 'aa_size',"\ "'F', 'nm_deaf', 'homogmy']"), sim.PyExec(r"F = 1.0-((genoFreq[0][(0,1)]+genoFreq[0][(1,0)])/" # F \ "(2.0*alleleFreq[0][0]*alleleFreq[0][1]))"\ "if alleleFreq[0][0] != 0.0 and alleleFreq[0][1]"\ "!= 0.0 else 0.0"), sim.PyExec(r"row += [gen, "\ "alleleFreq[0][0]," # A \ "alleleFreq[0][1]," # a \ "genoFreq[0][(0,0)]," # AA \ "genoFreq[0][(0,1)]+genoFreq[0][(1,0)]," # Aa \ "genoFreq[0][(1,1)]," # aa \ "genoNum[0][(0,0)]," # AA_size \ "genoNum[0][(0,1)]+genoNum[0][(1,0)]," # Aa_size \ "genoNum[0][(1,1)]," # aa_size \ "F if F>0.0 else 0.0," # F \ "num_deaf," # nm_deaf \ "homogamy]") # homogmy ], gen = generations ) return {'headers':pop.dvars().headers, 'row':pop.dvars().row}
def MutationSelection(N=1000, generations=10000, X_loci=100, A_loci=0, AgingModel='two_phases', seed=2001, reps=1, InitMutFreq=0.001, aging_a1=0.003, aging_a2=0.05, aging_b=-0.019, aging_k=0.1911, MutRate=0.001, StatsStep=100, OutPopPrefix='z1', PrintFreqs=False, debug=False): '''Creates and evolves a population to reach mutation-selection balance.''' if debug: sim.turnOnDebug('DBG_ALL') else: sim.turnOffDebug('DBG_ALL') sim.setRNG('mt19937', seed) pop = sim.Population(N, loci=[X_loci, A_loci], ploidy=2, chromTypes=[sim.CHROMOSOME_X, sim.AUTOSOME], infoFields=[ 'age', 'a', 'b', 'smurf', 'ind_id', 'father_id', 'mother_id', 'luck', 't0', 'fitness' ]) pop.setVirtualSplitter( sim.CombinedSplitter( splitters=[ sim.ProductSplitter(splitters=[ sim.InfoSplitter(field='age', cutoff=9), sim.InfoSplitter(field='smurf', values=[0, 1]) ]), sim.SexSplitter(), sim.InfoSplitter(field='age', values=0) ], vspMap=[(0), (2), (1, 3), (4), (5), (6)], names=['larvae', 'adults', 'smurfs', 'males', 'females', 'zero'])) pop.dvars().k = aging_k pop.dvars().N = N pop.dvars().seed = seed pop.dvars().X_loci = X_loci pop.dvars().A_loci = A_loci pop.dvars().AgingModel = AgingModel exec("import random\nrandom.seed(seed)", pop.vars(), pop.vars()) exec("import math", pop.vars(), pop.vars()) simu = sim.Simulator(pop, rep=reps) simu.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[1 - InitMutFreq, InitMutFreq]), sim.InitInfo([0], infoFields='age'), sim.InitInfo([aging_a1], infoFields='a'), sim.InitInfo([aging_b], infoFields='b'), sim.InitInfo(lambda: random.random(), infoFields='luck'), sim.InfoExec('t0 = -ind.b / ind.a', exposeInd='ind'), sim.InfoExec( 'smurf = 1.0 if AgingModel == "two_phases" and (ind.smurf == 1 or (ind.age > ind.t0 and ind.luck < 1.0 - math.exp(-ind.a * ind.age + ind.a * ind.t0 - ind.a / 2.0))) else 0.0', exposeInd='ind'), sim.IdTagger(), sim.PyExec('XFreqChange={}'), sim.PyExec('AFreqChange={}') ], preOps=[ sim.InfoExec('luck = random.random()'), sim.InfoExec( 'smurf = 1.0 if AgingModel == "two_phases" and (ind.smurf == 1 or (ind.age > ind.t0 and ind.luck < 1.0 - math.exp(-ind.a * ind.age + ind.a * ind.t0 - ind.a / 2.0))) else 0.0', exposeInd='ind'), sim.DiscardIf(natural_death(AgingModel)), sim.InfoExec('age += 1'), sim.PySelector(func=fitness_func1) ], matingScheme=sim.HeteroMating([ sim.CloneMating(subPops=[(0, 0), (0, 1), (0, 2)], weight=-1), sim.RandomMating(ops=[ sim.IdTagger(), sim.PedigreeTagger(), sim.InfoExec('smurf = 0.0'), sexSpecificRecombinator( rates=[0.75 / X_loci for x in range(X_loci)] + [2.07 / A_loci for x in range(A_loci)], maleRates=0.0), sim.PyQuanTrait(loci=sim.ALL_AVAIL, func=TweakAdditiveRecessive( aging_a1, aging_a2, aging_b, X_loci), infoFields=['a', 'b']) ], weight=1, subPops=[(0, 1)], numOffspring=1) ], subPopSize=demo), postOps=[ sim.SNPMutator(u=MutRate, subPops=[(0, 5)]), sim.Stat(alleleFreq=sim.ALL_AVAIL, step=StatsStep), sim.IfElse( 'X_loci > 0', ifOps=[ sim.PyExec( 'XFreqChange[gen] = [alleleFreq[x][1] for x in range(X_loci)]' ) ], elseOps=[sim.PyExec('XFreqChange[gen] = []')], step=StatsStep), sim.IfElse( 'A_loci > 0', ifOps=[ sim.PyExec( 'AFreqChange[gen] = [alleleFreq[a][1] for a in range(X_loci, pop.totNumLoci())]', exposePop='pop') ], elseOps=[sim.PyExec('AFreqChange[gen] = []')], step=StatsStep), sim.IfElse( PrintFreqs, ifOps=[ sim.PyEval( r"str(rep) + '\t' + str(gen) + '\t' + '\t'.join(map('{0:.4f}'.format, XFreqChange[gen])) + '\t\t' + '\t'.join(map('{0:.4f}'.format, AFreqChange[gen])) + '\n'" ) ], step=StatsStep), sim.TerminateIf( 'sum([alleleFreq[x][0] * alleleFreq[x][1] for x in range(X_loci + A_loci)]) == 0' ) ], gen=generations) i = 0 for pop in simu.populations(): pop.save('{}_{}.pop'.format(OutPopPrefix, i)) i += 1