def LC_evolve(popSize, alleleFreq, diseaseModel): ''' ''' pop = sim.Population( size=popSize, loci=[1] * len(alleleFreq), infoFields=['age', 'smoking', 'age_death', 'age_LC', 'LC']) pop.setVirtualSplitter( sim.CombinedSplitter(splitters=[ sim.InfoSplitter(field='age', cutoff=[20, 40], names=['youngster', 'adult', 'senior']), sim.SexSplitter(), sim.InfoSplitter(field='smoking', values=[0, 1, 2], names=['nonSmoker', 'smoker', 'formerSmoker']) ])) pop.evolve( initOps=[sim.InitSex(), sim.InitInfo(range(75), infoFields='age')] + [ sim.InitGenotype(freq=[1 - f, f], loci=i) for i, f in enumerate(alleleFreq) ] + [ sim.PyOperator(func=diseaseModel.initialize), ], preOps=[ sim.InfoExec('age += 1'), # die of lung cancer or natural death sim.DiscardIf('age > age_death') ], matingScheme=sim.HeteroMating( [ sim.CloneMating(weight=-1), sim.RandomMating(ops=[ sim.MendelianGenoTransmitter(), sim.PyOperator(func=diseaseModel.initialize) ], subPops=[(0, 'adult')]) ], subPopSize=lambda pop: pop.popSize() + popSize / 75), postOps=[ # update individual, currently ding nothing. sim.PyOperator(func=diseaseModel.updateStatus), # determine if someone has LC at his or her age sim.InfoExec('LC = age >= age_LC'), # get statistics about COPD and LC prevalence sim.Stat(pop, meanOfInfo='LC', subPops=[(0, sim.ALL_AVAIL)], vars=['meanOfInfo', 'meanOfInfo_sp']), sim.PyEval( r"'Year %d: Overall %.2f%% M: %.2f%% F: %.2f%% " r"NS: %.1f%%, S: %.2f%%\n' % (gen, meanOfInfo['LC']*100, " r"subPop[(0,3)]['meanOfInfo']['LC']*100," r"subPop[(0,4)]['meanOfInfo']['LC']*100," r"subPop[(0,5)]['meanOfInfo']['LC']*100," r"subPop[(0,6)]['meanOfInfo']['LC']*100)"), ], gen=100)
def setUp(self): self.pop = simu.Population(size=10, loci=1, infoFields='self_gen') self.sim = simu.Simulator(pops=self.pop) self.initOps = [ simu.InitSex(sex=[simu.MALE, simu.FEMALE]), simu.InitInfo(0, infoFields=['self_gen']) ] self.sexMode = (simu.GLOBAL_SEQUENCE_OF_SEX, simu.MALE, simu.FEMALE)
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]
def setUp(self): # A locus with 10 sites "Let there are 5 loci with 2 sites each" self.allele_length = 2 self.loci = 5 self.pop = simu.Population(size=10, loci=self.allele_length * self.loci, infoFields='self_gen') self.sim = simu.Simulator(pops=self.pop) self.initOps = [ simu.InitSex(sex=[simu.MALE, simu.FEMALE]), simu.InitInfo(0, infoFields=['self_gen']) ] self.sexMode = (simu.GLOBAL_SEQUENCE_OF_SEX, simu.MALE, simu.FEMALE)
sim.stat(pop, popSize=True, numOfAffected=True, subPops=[(0, sim.ALL_AVAIL)], vars=['popSize_sp', 'propOfAffected_sp']) for sp in range(3): print('%s: %.3f%% (size %d)' % (pop.subPopName((0,sp)), pop.dvars((0,sp)).propOfAffected * 100., pop.dvars((0,sp)).popSize)) # return True pop.evolve( initOps=[ sim.InitSex(), # random assign age sim.InitInfo(lambda: random.randint(0, 75), infoFields='age'), # random genotype sim.InitGenotype(freq=[0.5, 0.5]), # assign an unique ID to everyone. sim.IdTagger(), sim.PyOutput('Prevalence of disease in each age group:\n'), ], # increase the age of everyone by 1 before mating. preOps=sim.InfoExec('age += 1'), matingScheme=sim.HeteroMating([ # all individuals with age < 75 will be kept. Note that # CloneMating will keep individual sex, affection status and all # information fields (by default). sim.CloneMating(subPops=[(0,0), (0,1), (0,2)], weight=-1), # only individuals with age between 20 and 50 will mate and produce # offspring. The age of offspring will be zero.
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim import random pop = sim.Population([500], infoFields='anc') # Defines VSP 0, 1, 2, 3, 4 by anc. pop.setVirtualSplitter(sim.InfoSplitter('anc', cutoff=[0.2, 0.4, 0.6, 0.8])) # pop.evolve( initOps=[ sim.InitSex(), # anc is 0 or 1 sim.InitInfo(lambda : random.randint(0, 1), infoFields='anc') ], matingScheme=sim.RandomMating(ops=[ sim.MendelianGenoTransmitter(), sim.InheritTagger(mode=sim.MEAN, infoFields='anc') ]), postOps=[ sim.Stat(popSize=True, meanOfInfo='anc', varOfInfo='anc', subPops=[(0, sim.ALL_AVAIL)]), sim.PyEval(r"'Anc: %.2f (%.2f), #inds: %s\n' %" + \ "(meanOfInfo['anc'], varOfInfo['anc'], " + \ "', '.join(['%4d' % x for x in subPopSize]))") ], gen = 5, )
# This is to be able to call random from InfoExec: exec('import random', pop.vars(), pop.vars()) exec('import math', pop.vars(), pop.vars()) pop.dvars().k = args.k pop.dvars().model = args.model ############################################################### # SIMULATION # ############################################################### simu = sim.Simulator(pop, rep=args.replicates) simu.evolve( initOps = [ sim.InitInfo([0], infoFields = 'age'), sim.InitInfo([args.a], infoFields = 'a'), sim.InitInfo([args.b], infoFields = 'b'), sim.InitInfo(lambda: random.random(), infoFields = 'luck'), sim.InfoExec("t0 = -ind.b / ind.a", exposeInd = 'ind'), sim.InfoExec("smurf = 1 if (model == 'two_phases' and 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", exposeInd = 'ind'), sim.PyExec("Surviving = {'larvae': [], 'adults': [], 'smurfs': []}") ], preOps = [ sim.InfoExec("luck = random.random()"), sim.InfoExec("smurf = 1 if ((ind.smurf == 1) or (model == 'two_phases' and 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", exposeInd='ind'), sim.DiscardIf(aging_model(args.model)), sim.InfoExec("age += 1") ], matingScheme = sim.CloneMating(subPops = sim.ALL_AVAIL, subPopSize = demo), postOps = [
# choose another parent p2 = inds[randint(0, len(inds) - 1)] # return indexes of both parents if s1 == sim.MALE: yield p1, p2 else: yield p2, p1 pop = sim.Population(size=2000, loci=1, infoFields='x') # define VSPs x<1, 1<=x<2, 2<=x<3, 3<=x<4, ... pop.setVirtualSplitter(sim.InfoSplitter(field='x', cutoff=range(1, 8))) pop.evolve( initOps=[ sim.InitSex(), sim.InitInfo(lambda: uniform(0, 8), infoFields='x'), # only individuals in the middle range has certain genotype sim.InitGenotype(freq=[0.6, 0.4], subPops=[(0, 4)]), ], matingScheme=VicinityMating(locationField='x', vicinity=1, varOfLocation=0.5), postOps=[ sim.Stat(alleleFreq=0, subPops=[(0, sim.ALL_AVAIL)], vars='alleleFreq_sp'), sim.PyEval(r"'%.3f ' % alleleFreq[0][1]", subPops=[(0, sim.ALL_AVAIL)]), sim.PyOutput('\n'), ], gen=10)
def recurrent_drift(self, pop, meta_pop, qtl, aes, recombination_rates): """ Sets up and runs recurrent selection for a number of generations for a single replicate population. Samples individuals at specified intervals to make a ``meta_pop``. :param pop: Population which undergoes selection. :param meta_pop: Population into which sampled individuals are deposited :param qtl: List of loci to which allele effects have been assigned :param aes: Dictionary of allele effects """ pop.dvars().gen = 0 meta_pop.dvars().gen = 0 sizes = [self.individuals_per_breeding_subpop] \ * self.number_of_breeding_subpops + \ [self.number_of_nonbreeding_individuals] offspring_pops = [self.offspring_per_breeding_subpop] \ * self.number_of_breeding_subpops + [0] assert len(sizes) == len(offspring_pops), "Number of parental " \ "subpopulations must equal " \ "the number of offspring " \ "subpopulations" sampling_generations = [ i for i in range(2, self.generations_of_drift, 2) ] pc = breed.HalfSibBulkBalanceChooser( self.individuals_per_breeding_subpop, self.offspring_per_female) pop.evolve( initOps=[ sim.InitInfo(0, infoFields=['generation']), operators.GenoAdditiveArray(qtl, aes), operators.CalculateErrorVariance(self.heritability), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.MetaPopulation(meta_pop, self.meta_pop_sample_sizes), sim.PyEval(r'"Initial: Sampled %d individuals from generation ' r'%d Replicate: %d.\n" % (ss, gen_sampled_from, ' r'rep)'), ], preOps=[ sim.PyEval(r'"Generation: %d\n" % gen'), operators.GenoAdditiveArray(qtl, aes, begin=1), sim.InfoExec('generation=gen'), operators.PhenotypeCalculator( self.proportion_of_individuals_saved, begin=1), operators.MetaPopulation(meta_pop, self.meta_pop_sample_sizes, at=sampling_generations), sim.SplitSubPops(sizes=sizes, randomize=True), ], matingScheme=sim.HomoMating( sim.PyParentsChooser(pc.recursive_pairwise_parent_chooser), sim.OffspringGenerator(ops=[ sim.IdTagger(), sim.PedigreeTagger(), sim.Recombinator(rates=recombination_rates) ], numOffspring=1), subPopSize=offspring_pops, subPops=list(range(1, self.number_of_breeding_subpops, 1))), postOps=[ sim.MergeSubPops(), operators.DiscardRandomOffspring( self.number_of_offspring_discarded), ], finalOps=[ sim.InfoExec('generation=gen'), operators.GenoAdditive(qtl, aes), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.MetaPopulation(meta_pop, self.meta_pop_sample_sizes), sim.PyEval( r'"Final: Sampled %d individuals from generation %d\n" ' r'% (ss, gen_sampled_from)'), ], gen=self.generations_of_drift)
female = females[randint(0, len(females) - 1)] if female.pod != pod: break yield (male, female) pop = sim.Population(5000, loci=[1, 1], infoFields=['pod'], chromTypes=[sim.AUTOSOME, sim.CUSTOMIZED]) pop.setVirtualSplitter(sim.InfoSplitter('pod', values=range(5))) pop.evolve( initOps=[ sim.InitSex(), # assign individuals to a random pod sim.InitInfo(lambda: randint(0, 4), infoFields='pod'), # only the first pod has the disease alleles sim.InitGenotype(freq=[0.8, 0.2], subPops=[(0, 0)]), ], matingScheme=sim.HomoMating( sim.PyParentsChooser(podParentsChooser), sim.OffspringGenerator( numOffspring=1, ops=[ sim.MendelianGenoTransmitter(), sim.MitochondrialGenoTransmitter(), # offspring stays with their natal pod sim.InheritTagger(mode=sim.MATERNAL, infoFields='pod') ])), postOps=[ # calulate allele frequency at each pod
import random def randomMove(x, y): '''Pass parental information fields to offspring''' # shift right with high concentration of alleles... off_x = random.normalvariate((x[0] + x[1]) / 2., 0.1) off_y = random.normalvariate((y[0] + y[1]) / 2., 0.1) return off_x, off_y pop = sim.Population(1000, loci=[1], infoFields=['x', 'y']) pop.setVirtualSplitter( sim.GenotypeSplitter(loci=0, alleles=[[0, 0], [0, 1], [1, 1]])) pop.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[0.5, 0.5]), sim.InitInfo(random.random, infoFields=['x', 'y']) ], matingScheme=sim.RandomMating(ops=[ sim.MendelianGenoTransmitter(), sim.PyTagger(func=randomMove), ]), postOps=[ sim.Stat(minOfInfo='x', maxOfInfo='x'), sim.PyEval( r"'Range of x: %.2f, %.2f\n' % (minOfInfo['x'], maxOfInfo['x'])") ], gen=5)
names=['larvae', 'adults', 'smurfs', 'males', 'females'])) # This is to be able to call random and math from InfoExec: exec("import random", pop.vars(), pop.vars()) exec("import math", pop.vars(), pop.vars()) ############################################################### # SIMULATION # ############################################################### simu = sim.Simulator(pop, 1) simu.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[1.0 - args.initfreq, args.initfreq]), sim.InitInfo([0], infoFields='age'), sim.InitInfo([1], infoFields='fitness'), sim.InitInfo([0], infoFields='birthday'), # At this point, even males are diploids! Only 1/1 and 1/0 (but not 0/1) males get 'a' increased. sim.InfoExec( "a = min_a + meffect if ind.sex() == 1 and ind.allele(0,0) == 1 else min_a", exposeInd='ind'), sim.InitInfo([args.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 (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.PedigreeTagger(output='>>{}.ped'.format(args.output), outputFields=['a', 'birthday'],
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
def replicate_recurrent_drift(self, multi_pop, meta_sample_library, qtl, allele_effects, recombination_rates): """ :param multi_pop: :param meta_pop_sample_library: :param qtl: :param allele_effects: :param recombination_rates: :return: """ for pop in multi_pop.populations(): pop.dvars().gen = 0 sizes = [self.individuals_per_breeding_subpop] \ * self.number_of_breeding_subpops + \ [self.number_of_nonbreeding_individuals] offspring_pops = [self.offspring_per_breeding_subpop] \ * self.number_of_breeding_subpops + [0] assert len(sizes) == len(offspring_pops), "Number of parental " \ "subpopulations must equal " \ "the number of offspring " \ "subpopulations" sampling_generations = [ i for i in range(2, self.generations_of_drift, 2) ] pc = breed.HalfSibBulkBalanceChooser( self.individuals_per_breeding_subpop, self.offspring_per_female) multi_pop.evolve( initOps=[ sim.InitInfo(0, infoFields=['generation']), sim.InfoExec('replicate=rep'), operators.GenoAdditiveArray(qtl, allele_effects), operators.CalculateErrorVariance(self.heritability), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes), sim.PyEval(r'"Initial: Sampled %d individuals from generation ' r'%d Replicate: %d.\n" % (ss, gen_sampled_from, ' r'rep)'), ], preOps=[ sim.PyEval(r'"Generation: %d\n" % gen'), operators.GenoAdditiveArray(qtl, allele_effects, begin=1), sim.InfoExec('generation=gen'), sim.InfoExec('replicate=rep'), operators.PhenotypeCalculator( self.proportion_of_individuals_saved, begin=1), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes, at=sampling_generations), sim.SplitSubPops(sizes=sizes, randomize=False), ], matingScheme=sim.HomoMating( sim.PyParentsChooser(pc.recursive_pairwise_parent_chooser), sim.OffspringGenerator(ops=[ sim.IdTagger(), sim.PedigreeTagger(), sim.Recombinator(rates=recombination_rates) ], numOffspring=1), subPopSize=offspring_pops, subPops=list(range(1, self.number_of_breeding_subpops, 1))), postOps=[ sim.MergeSubPops(), operators.DiscardRandomOffspring( self.number_of_offspring_discarded), ], finalOps=[ sim.InfoExec('generation=gen'), sim.InfoExec('replicate=rep'), operators.GenoAdditiveArray(qtl, allele_effects), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes), sim.PyEval( r'"Final: Sampled %d individuals from generation %d\n" ' r'% (ss, gen_sampled_from)'), ], gen=self.generations_of_drift)
females.append([x for x in pop.individuals(subPop) \ if x.sex() == sim.FEMALE and x.rank == rank]) # while True: # choose a rank randomly rank = int( pop.individual(randint(0, pop.subPopSize(subPop) - 1), subPop).rank) yield males[rank][randint(0, len(males[rank]) - 1)], \ females[rank][randint(0, len(females[rank]) - 1)] def setRank(rank): 'The rank of offspring can increase or drop to zero randomly' # only use rank of the father return (rank[0] + randint(-1, 1)) % 3 pop = sim.Population(size=[1000, 2000], loci=1, infoFields='rank') pop.evolve(initOps=[ sim.InitSex(), sim.InitInfo(lambda: randint(0, 2), infoFields='rank') ], matingScheme=sim.HomoMating( sim.PyParentsChooser(randomChooser), sim.OffspringGenerator(ops=[ sim.MendelianGenoTransmitter(), sim.PyTagger(setRank), ])), gen=5)
for sp in range(pop.numSubPop()): # get source subpop for all individuals in subpopulation i origins = pop.indInfo('migrate_from', sp) spSize = pop.subPopSize(sp) B_sp = [ origins.count(j) * 1.0 / spSize for j in range(pop.numSubPop()) ] print(' ' + ', '.join(['{:.3f}'.format(x) for x in B_sp])) return True pop.evolve( initOps=sim.InitSex(), preOps= # mark the source subpopulation of each individual [sim.InitInfo(i, subPops=i, infoFields='migrate_from') for i in range(3)] + [ # perform migration sim.BackwardMigrator( rate=[[0, 0.04, 0.02], [0.05, 0, 0.02], [0.02, 0.01, 0]]), # calculate and print observed backward migration matrix sim.PyOperator(func=originOfInds), # calculate population size sim.Stat(popSize=True), # and print it sim.PyEval( r'"Pop size after migration: {}\n".format(", ".join([str(x) for x in subPopSize]))' ), ], matingScheme=sim.RandomMating(), gen=5)
# BB Bb bb # AA 1 1 1 # Aa 1 1-s1 1-s2 # aa 1 1 1-s2 # # geno is (A1 A2 B1 B2) if geno[0] + geno[1] == 1 and geno[2] + geno[3] == 1: v = 1 - s1 # case of AaBb elif geno[2] + geno[3] == 2: v = 1 - s2 # case of ??bb else: v = 1 # other cases if smoking: return v * 0.9 else: return v pop.evolve( initOps=[sim.InitSex(), sim.InitGenotype(freq=[.5, .5])], preOps=sim.PySelector(loci=[0, 1], func=sel), matingScheme=sim.RandomMating(), postOps=[ # set smoking status randomly sim.InitInfo(lambda: random.randint(0, 1), infoFields='smoking'), sim.Stat(alleleFreq=[0, 1], step=20), sim.PyEval(r"'%.4f\t%.4f\n' % (alleleFreq[0][1], alleleFreq[1][1])", step=20) ], gen=50)
def replicate_random_mating(self, multi_pop, meta_sample_library, qtl, allele_effects, recombination_rates): """ Runs recurrent truncation selection on a multi-replicate population. :param multi_pop: Simulator object of full-sized population :param meta_sample_library: Simulator object of meta-populations :param qtl: Loci whose alleles have effects :param allele_effects: Allele effect container :param recombination_rates: Probabilities for recombination at each locus """ for pop_rep in multi_pop.populations(): pop_rep.dvars().gen = 0 sizes = [self.individuals_per_breeding_subpop] \ * self.number_of_breeding_subpops + \ [self.number_of_nonbreeding_individuals] offspring_pops = [self.offspring_per_breeding_subpop] \ * self.number_of_breeding_subpops + [0] assert len(sizes) == len(offspring_pops), "Number of parental " \ "subpopulations must equal " \ "the number of offspring " \ "subpopulations" sampling_generations = [ i for i in range(2, self.generations_of_random_mating, 2) ] multi_pop.evolve( initOps=[ sim.InitInfo(0, infoFields=['generation']), sim.InfoExec('replicate=rep'), operators.GenoAdditiveArray(qtl, allele_effects), operators.CalculateErrorVariance(self.heritability), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes), sim.PyEval(r'"Initial: Sampled %d individuals from generation ' r'%d Replicate: %d.\n" % (ss, gen_sampled_from, ' r'rep)'), ], preOps=[ sim.PyEval(r'"Generation: %d\n" % gen'), operators.GenoAdditiveArray(qtl, allele_effects, begin=1), sim.InfoExec('generation=gen'), sim.InfoExec('replicate=rep'), operators.PhenotypeCalculator( self.proportion_of_individuals_saved, begin=1), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes, at=sampling_generations), ], matingScheme=sim.RandomMating(ops=[ sim.IdTagger(), sim.PedigreeTagger(), sim.Recombinator(rates=recombination_rates) ]), finalOps=[ sim.InfoExec('generation=gen'), sim.InfoExec('replicate=rep'), operators.GenoAdditiveArray(qtl, allele_effects), operators.PhenotypeCalculator( self.proportion_of_individuals_saved), operators.ReplicateMetaPopulation(meta_sample_library, self.meta_pop_sample_sizes), sim.PyEval( r'"Final: Sampled %d individuals from generation %d\n" ' r'% (ss, gen_sampled_from)'), ], gen=self.generations_of_random_mating)