def checkNumOffspring(numOffspring, ops=[]): '''Check the number of offspring for each family using information field father_idx ''' pop = sim.Population(size=[30], loci=1, infoFields=['father_idx', 'mother_idx']) pop.evolve(initOps=[ sim.InitSex(), sim.InitGenotype(freq=[0.5, 0.5]), ], matingScheme=sim.RandomMating(ops=[ sim.MendelianGenoTransmitter(), sim.ParentsTagger(), ] + ops, numOffspring=numOffspring), gen=1) # get the parents of each offspring parents = [ (x, y) for x, y in zip(pop.indInfo('mother_idx'), pop.indInfo('father_idx')) ] # Individuals with identical parents are considered as siblings. famSize = [] lastParent = (-1, -1) for parent in parents: if parent == lastParent: famSize[-1] += 1 else: lastParent = parent famSize.append(1) return famSize
def _make_pop(popsize, nloci, locus_position, id_tagger, init_geno, recomb_rate, generations, length, init_ts): random.seed(123) pop = sim.Population(size=[popsize], loci=[nloci], lociPos=locus_position, infoFields=['ind_id']) # tag the first generation so we can pass it to rc id_tagger.apply(pop) first_gen = pop.indInfo("ind_id") haploid_labels = [(k, p) for k in first_gen for p in (0, 1)] node_ids = {x: j for x, j in zip(haploid_labels, init_ts.samples())} rc = ftprime.RecombCollector(ts=init_ts, node_ids=node_ids, locus_position=locus_position) recombinator = sim.Recombinator(intensity=recomb_rate, output=rc.collect_recombs, infoFields="ind_id") pop.evolve( initOps=[sim.InitSex()] + init_geno, preOps=[ sim.PyOperator(lambda pop: rc.increment_time() or True), # Must return true or false. True keeps whole population (?) ], matingScheme=mating_scheme_factory(recombinator, popsize, id_tagger), postOps=[sim.PyEval(r"'Gen: %2d\n' % (gen, )", step=1)], gen=generations) return pop, rc
def simulate(model, N0, N1, G0, G1, spec, s, mu, k): '''Evolve a sim.Population using given demographic model and observe the evolution of its allelic spectrum. model: type of demographic model. N0, N1, G0, G1: parameters of demographic model. spec: initial allelic spectrum, should be a list of allele frequencies for each allele. s: selection pressure. mu: mutation rate. k: k for the k-allele model ''' demo_func = demo_model(model, N0, N1, G0, G1) pop = sim.Population(size=demo_func(0), loci=1, infoFields='fitness') pop.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=spec, loci=0) ], matingScheme=sim.RandomMating(subPopSize=demo_func), postOps=[ sim.KAlleleMutator(k=k, rates=mu), sim.MaSelector(loci=0, fitness=[1, 1, 1 - s], wildtype=0), ne(loci=[0], step=100), sim.PyEval(r'"%d: %.2f\t%.2f\n" % (gen, 1 - alleleFreq[0][0], ne[0])', step=100), ], gen = G0 + G1 )
def checkSexMode(ms): '''Check the assignment of sex to offspring''' pop = sim.Population(size=[40]) pop.evolve(initOps=sim.InitSex(), matingScheme=ms, gen=1) # return individual sex as a string return ''.join( ['M' if ind.sex() == sim.MALE else 'F' for ind in pop.individuals()])
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 initialize_tuson_pop(self, chromosome_lengths, info_fields, all_genotypes_handle): tuson_founders = sim.Population(size=105, loci=chromosome_lengths, infoFields=info_fields) for ind, genotype in zip(tuson_founders.individuals(), all_genotypes_handle): ind.setGenotype(genotype) sim.tagID(tuson_founders, reset=True) return tuson_founders
def get_mean_r2(Ne, S, n_loci, gens, n_subpops, initial_frequencies, m): """Returns the mean r2 value for each subpopulation, in list of length n_subpops""" # make pairwise migration matrix M = get_migration_matrix(m, n_subpops) # initialise population n_alleles = 2 pop = sim.Population(size=[Ne] * n_subpops, ploidy=2, loci=[1] * n_loci, alleleNames=[str(i) for i in range(n_alleles)], infoFields='migrate_to') sim.initGenotype(pop, freq=[initial_frequencies, 1 - initial_frequencies]) #sim.initGenotype(pop, freq = [1/n_alleles for i in range(n_alleles)]) sim.initSex(pop) print(M) # run burn in generations pop.evolve(initOps=[], preOps=sim.Migrator(M, mode=sim.BY_PROBABILITY), matingScheme=sim.RandomMating(), gen=gens) # take sample from each subpopulation sample_pop = drawRandomSample(pop, sizes=[S] + [0] * (n_subpops - 1)) #sim.dump(sample_pop) # get allele frequencies sim.stat(sample_pop, alleleFreq=range(0, n_loci), vars=['alleleFreq_sp']) #print(sample_pop.dvars(0).alleleFreq) # calculate r2 values sim.stat(sample_pop, LD=list(itertools.combinations(list(range(n_loci)), r=2)), vars=['R2_sp']) #print(sample_pop.dvars(0).R2) r2s = [] for sp in [0]: #range(n_subpops*0): allele_freqs = sample_pop.dvars(sp).alleleFreq seg_alleles = [ k for k in range(n_loci) if np.abs(.5 - allele_freqs[k][0]) < .5 - 0.05 ] if len(seg_alleles) < 2: raise Exception("<2 segregating alleles") r2_sum = 0 count = 0 for pairs in itertools.combinations(seg_alleles, r=2): r2_sum += sample_pop.dvars(sp).R2[pairs[0]][pairs[1]] count += 1 mean_r2 = r2_sum / count r2s.append(mean_r2) return r2s
def _create_single_pop(self, pop_size, nloci): init_ops = [] init_ops.append(sp.InitSex()) pop = sp.Population(pop_size, ploidy=2, loci=[1] * nloci, chromTypes=[sp.AUTOSOME] * nloci, infoFields=list(self._info_fields)) pre_ops = [] post_ops = [] return pop, init_ops, pre_ops, post_ops
def get_FCs(Ne, S, n_loci, gens, n_subpops, initial_frequencies, m): ''''Runs simulations for allelic fluctuations model with n subpopulations, and returns a list of FC values (one for each subpopulation)''' # population to evolve ((from infinite gamete pool)) popNe = sim.Population(size=[Ne] * n_subpops, ploidy=2, loci=[1] * n_loci, infoFields='migrate_to') # initial sample population (from infinite gamete pool) popS = sim.Population(size=[S] * n_subpops, ploidy=2, loci=[1] * n_loci) sim.initGenotype(popNe, freq=initial_frequencies) sim.initGenotype(popS, freq=initial_frequencies) # get initial sample allele frequencies sim.stat(popS, alleleFreq=range(n_loci), vars=['alleleFreq_sp']) M = get_migration_matrix(m, n_subpops) popNe.evolve(initOps=[sim.InitSex()], preOps=sim.Migrator(rate=M), matingScheme=sim.RandomMating(), gen=gens) sample_pop = drawRandomSample(popNe, sizes=[S] * n_subpops) sim.stat(sample_pop, alleleFreq=range(n_loci), vars=['alleleFreq_sp']) all_FCs = [] for sp in range(n_subpops): initial_allele_frequencies = popS.dvars(sp).alleleFreq final_allele_frequencies = sample_pop.dvars(sp).alleleFreq sp_count = 0 sp_FC = 0 for locus in range(n_loci): init_pair = repair(initial_allele_frequencies[locus]) end_pair = repair(final_allele_frequencies[locus]) if init_pair[0]**2 + init_pair[1]**2 != 1: sp_FC += fc_variant([init_pair[0], init_pair[1]], [end_pair[0], end_pair[1]]) sp_count += 1 all_FCs.append(sp_FC / sp_count) return all_FCs
def _create_island(self, pop_sizes, mig, nloci): init_ops = [] init_ops.append(sp.InitSex()) pop = sp.Population(pop_sizes, ploidy=2, loci=[1] * nloci, chromTypes=[sp.AUTOSOME] * nloci, infoFields=list(self._info_fields)) post_ops = [sp.Migrator( demography.migrIslandRates(mig, len(pop_sizes)))] pre_ops = [] self._info_fields.add('migrate_to') return pop, init_ops, pre_ops, post_ops
def allelesToMutants(pop, regions, logger=None): '''Convert a population from allele space to mutational space, using specified regions. ''' pops = [] for region in regions: loci = [] ch_name = region.split(':')[0][3:] start, end = [int(x) for x in region.split(':')[1].split('..')] try: ch = pop.chromByName(ch_name) except: raise ValueError( 'Chromosome %s is not available in passed population.' % ch_name) for loc in range(pop.chromBegin(ch), pop.chromEnd(ch)): pos = pop.locusPos(loc) if pos >= start and pos <= end: loci.append(loc) # get the mutants for each individual allAlleles = [] for ind in pop.individuals(): alleles0 = [] alleles1 = [] for loc in loci: if ind.allele(loc, 0) != 0: alleles0.append(int(pop.locusPos(loc))) if ind.allele(loc, 1) != 0: alleles1.append(int(pop.locusPos(loc))) allAlleles.extend([alleles0, alleles1]) # maximum number of mutants maxMutants = max([len(x) for x in allAlleles]) if logger is not None: logger.info( '%d loci are identified with at most %d mutants in region %s.' % (len(loci), maxMutants, region)) # create a population mpop = sim.Population(pop.popSize(), loci=maxMutants, chromNames=region) # put in mutants for idx, ind in enumerate(mpop.individuals()): geno = ind.genotype(0) for loc, mut in enumerate(allAlleles[idx * 2]): geno[loc] = mut geno = ind.genotype(1) for loc, mut in enumerate(allAlleles[idx * 2 + 1]): geno[loc] = mut pops.append(mpop) # merge all populations into one for pop in pops[1:]: pops[0].addChromFrom(pop) return pops[0]
def simulate(demo, gen): pop = sim.Population(size=demo(0)) pop.evolve(initOps=sim.InitSex(), preOps=[ sim.Stat(popSize=True), sim.PyEval(r"'%d: %d ' % (gen, popSize)"), ], matingScheme=sim.RandomMating(subPopSize=demo), postOps=[ sim.Stat(popSize=True), sim.PyEval(r"'--> %d\n' % popSize"), ], gen=gen)
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 test_slice_transition(self): init_population_sizes = self.net_model.get_initial_size() log.info("init_pop_sizes: %s", init_population_sizes) names = self.net_model.get_subpopulation_names() pop = sim.Population(size=init_population_sizes, subPopNames=names, infoFields=self.net_model.get_info_fields()) for time in range(1, self.end_sim): pop.dvars().gen = time self.net_model(pop) log.info("time: %s subpop names: %s subpop sizes: %s", time, self.net_model.get_subpopulation_names(), self.net_model.get_subpopulation_sizes())
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)
def get_mean_r2(Ne, S, n_loci, gens, repeats, n_subpops, initial_frequencies, m): M = get_migration_matrix(m, n_subpops) pop = sim.Population(size=[Ne] * n_subpops, ploidy=2, loci=[1] * n_loci, infoFields='migrate_to') sim.initGenotype(pop, freq=initial_frequencies) pop.evolve( initOps=[sim.InitSex(), sim.InitGenotype(freq=initial_frequencies)], preOps=sim.Migrator(rate=M), matingScheme=sim.RandomMating(), gen=gens) sample_pop = drawRandomSample(pop, sizes=[S] * n_subpops) # get allele frequencies sim.stat(sample_pop, alleleFreq=range(0, n_loci), vars=['alleleFreq_sp']) # calculate r2 values sim.stat(sample_pop, LD=list(combinations(list(range(n_loci)), r=2)), vars=['R2_sp']) r2s = [] for sp in range(n_subpops): allele_freqs = sample_pop.dvars(sp).alleleFreq seg_alleles = [ k for k in range(n_loci) if np.abs(.5 - allele_freqs[k][0]) < .5 - 0.05 ] if len(seg_alleles) < 2: raise Exception("<2 segregating alleles") r2_sum = count = 0 for pairs in combinations(seg_alleles, r=2): r2_sum += sample_pop.dvars(sp).R2[pairs[0]][pairs[1]] count += 1 mean_r2 = r2_sum / count r2s.append(mean_r2) return r2s
def mutantsToAlleles(pop, logger): '''Convert a population from mutational space to allele space. Monomorphic markers are ignored. ''' # figure out chromosomes and markers markers = {} for ch, region in enumerate(pop.chromNames()): chNumber = region.split(':')[0][3:] loci = set() for ind in pop.individuals(): loci |= set(ind.genotype(0, ch)) loci |= set(ind.genotype(1, ch)) if chNumber in markers: markers[chNumber] |= loci else: markers[chNumber] = loci # create a population for each chromosome pops = [] chroms = list(markers.keys()) chroms.sort() for ch in chroms: markers[ch] = list(markers[ch]) markers[ch].remove(0) markers[ch].sort() if logger: logger.info('Chromosome %s has %d markers' % (ch, len(markers[ch]))) apop = sim.Population(pop.popSize(), loci=len(markers[ch]), lociPos=markers[ch]) # get a dictionary of loci position lociPos = {} for idx, loc in enumerate(apop.lociPos()): lociPos[loc] = idx for aind, mind in zip(apop.individuals(), pop.individuals()): for p in range(2): for mutant in mind.genotype(p): if mutant != 0: aind.setAllele(1, lociPos[mutant], p) pops.append(apop) for pop in pops[1:]: pops[0].addChromFrom(pop) return pops[0]
def createSinglePop(popSize, nLoci, startLambda=99999, lbd=1.0): initOps = [sp.InitSex(maleFreq=cfg.maleProb)] if startLambda < 99999: preOps = [sp.ResizeSubPops(proportions=(float(lbd), ), begin=startLambda)] else: preOps = [] postOps = [] pop = sp.Population(popSize, ploidy=2, loci=[1] * nLoci, chromTypes=[sp.AUTOSOME] * nLoci, infoFields=["ind_id", "father_id", "mother_id", "age", "breed", "rep_succ", "mate", "force_skip"]) for ind in pop.individuals(): ind.breed = -1000 oExpr = ('"%s/samp/%f/%%d/%%d/smp-%d-%%d-%%d.txt" %% ' + '(numIndivs, numLoci, gen, rep)') % ( cfg.dataDir, cfg.mutFreq, popSize) return pop, initOps, preOps, postOps, oExpr
def _create_stepping_stone(self, pop_sizes, mig, nloci): if len(pop_sizes) == 1: flat_pop_sizes = pop_sizes[0] post_ops = [sp.Migrator( demography.migrSteppingStoneRates(mig, len(flat_pop_sizes)))] else: flat_pop_sizes = [] for line in pop_sizes: flat_pop_sizes.extend(line) post_ops = [sp.Migrator( demography.migr2DSteppingStoneRates(mig, len(pop_sizes), len(pop_sizes[0])))] init_ops = [] init_ops.append(sp.InitSex()) pop = sp.Population(flat_pop_sizes, ploidy=2, loci=[1] * nloci, chromTypes=[sp.AUTOSOME] * nloci, infoFields=list(self._info_fields)) pre_ops = [] self._info_fields.add('migrate_to') return pop, init_ops, pre_ops, post_ops
def importData(filename): 'Read data from ``filename`` and create a population' data = open(filename) header = data.readline() fields = header.split(',') # columns 1, 3, 5, ..., without trailing '_1' names = [fields[x].strip()[:-2] for x in range(1, len(fields), 2)] popSize = 0 alleleNames = set() for line in data.readlines(): # get all allele names alleleNames |= set([x.strip() for x in line.split(',')[1:]]) popSize += 1 # create a population alleleNames = list(alleleNames) pop = sim.Population(size=popSize, loci=len(names), lociNames=names, alleleNames=alleleNames,chromTypes=sim.CHROMOSOME_X,infoFields='fitness') # start from beginning of the file again data.seek(0) # discard the first line data.readline() for ind, line in zip(pop.individuals(), data.readlines()): fields = [x.strip() for x in line.split(',')] if fields[0] == '1': sex = sim.MALE ploidy0 = [alleleNames.index(fields[x]) for x in range(1, len(fields), 2)] ind.setGenotype(ploidy0, 0) ind.setSex(sex) else: sex = sim.FEMALE ploidy0 = [alleleNames.index(fields[x]) for x in range(1, len(fields), 2)] ploidy1 = [alleleNames.index(fields[x]) for x in range(2, len(fields), 2)] ind.setGenotype(ploidy0, 0) ind.setGenotype(ploidy1, 1) ind.setSex(sex) # close the file data.close() return pop
import simuPOP as sim from simuPOP.utils import migrIslandRates p = [0.2, 0.3, 0.5] pop = sim.Population(size=[10000] * 3, loci=1, infoFields='migrate_to') simu = sim.Simulator(pop, rep=2) simu.evolve( initOps=[sim.InitSex()] + [sim.InitGenotype(prop=[p[i], 1 - p[i]], subPops=i) for i in range(3)], preOps=sim.Migrator(rate=migrIslandRates(0.01, 3), reps=0), matingScheme=sim.RandomMating(), postOps=[ sim.Stat(alleleFreq=0, structure=0, vars='alleleFreq_sp', step=50), sim.PyEval( "'Fst=%.3f (%s)\t' % (F_st, ', '.join(['%.2f' % " "subPop[x]['alleleFreq'][0][0] for x in range(3)]))", step=50), sim.PyOutput('\n', reps=-1, step=50), ], gen=201)
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This script is an example in the simuPOP user's guide. Please refer to # the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim from pprint import pprint pop = sim.Population(100, loci=2) sim.initGenotype(pop, freq=[0.3, 0.7]) print(pop.vars()) # No variable now pop.dvars().myVar = 21 print(pop.vars()) sim.stat(pop, popSize=1, alleleFreq=0) # pprint prints in a less messy format pprint(pop.vars()) # print number of allele 1 at locus 0 print(pop.vars()['alleleNum'][0][1]) # use the dvars() function to access dictionary keys as attributes print(pop.dvars().alleleNum[0][1]) print(pop.dvars().alleleFreq[0])
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This script is an example in the simuPOP user's guide. Please refer to # the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim import random def demo(pop): return [x + random.randint(50, 100) for x in pop.subPopSizes()] pop = sim.Population(size=[500, 1000], infoFields='migrate_to') pop.evolve( initOps=sim.InitSex(), matingScheme=sim.RandomMating(subPopSize=demo), postOps=[ sim.Stat(popSize=True), sim.PyEval(r'"%s\n" % subPopSize') ], gen = 3 )
counter = defaultdict(int) def countMutants(mutants): global counter for line in mutants.split('\n'): # a trailing \n will lead to an empty string if not line: continue (gen, loc, ploidy, a1, a2, id) = line.split('\t') counter[int(loc)] += 1 pop = sim.Population( [5000] * 3, loci=[2, 1, 1], infoFields='ind_id', chromTypes=[sim.AUTOSOME, sim.CHROMOSOME_X, sim.CHROMOSOME_Y]) pop.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[0.5, 0.5]), sim.IdTagger(), ], preOps=[ sim.KAlleleMutator(rates=[0.001] + [0.01] * 3, loci=range(4), k=100, output=countMutants), ], matingScheme=sim.RandomMating(
import simuOpt simuOpt.setOptions(quiet=True, alleleType='long') import simuPOP as sim pop = sim.Population(size=[2500]*10, loci=1) simu = sim.Simulator(pop, rep=2) simu.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(genotype=20), ], preOps=[ sim.StepwiseMutator(rates=0.0001, reps=0), sim.KAlleleMutator(k=10000, rates=0.0001, reps=1), ], matingScheme=sim.RandomMating(), postOps=[ # Use vars=['alleleFreq_sp'] to calculate allele frequency for # each subpopulation sim.Stat(alleleFreq=0, vars=['alleleFreq_sp'], step=200), sim.PyEval('gen', step=200, reps=0), sim.PyEval(r"'\t%.2f' % (sum([len(subPop[x]['alleleFreq'][0]) " "for x in range(10)])/10.)", step=200), sim.PyOutput('\n', reps=-1, step=200) ], gen=601 )
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This script is an example in the simuPOP user's guide. Please refer to # 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(size=[200, 200], loci=[5, 5], infoFields='age') sim.initGenotype(pop, genotype=range(10)) sim.initInfo(pop, lambda: random.randint(0, 75), infoFields='age') pop.setVirtualSplitter(sim.InfoSplitter(field='age', cutoff=[20, 60])) # remove individuals pop.removeIndividuals(indexes=range(0, 300, 10)) print(pop.subPopSizes()) # remove individuals using IDs pop.setIndInfo([1, 2, 3, 4], field='age') pop.removeIndividuals(IDs=[2, 4], idField='age') # remove indiviuals using a filter function sim.initSex(pop) pop.removeIndividuals(filter=lambda ind: ind.sex() == sim.MALE) print([pop.individual(x).sex() for x in range(8)]) # # remove subpopulation
def simulation(self): self.pop = sim.Population(size = [500, 500], loci=[1]*20, infoFields = ["age",'ind_id', 'father_idx', 'mother_idx', "hc", "ywc",'migrate_to'], subPopNames = ["croatia", "slovenia"]) sim.initInfo(pop = self.pop, values = list(map(int, np.random.negative_binomial(n = 1, p = 0.25, size=500))), infoFields="age") self.pop.setVirtualSplitter(sim.CombinedSplitter([ sim.ProductSplitter([ sim.SexSplitter(), sim.InfoSplitter(field = "age", cutoff = [1,3,6,10])])], vspMap = [[0,1], [2], [3], [4], [5,6,7,8], [9] ])) # Age groups: from 0 to 1 - cubs, from 1 to 3 - prereproductive, from 3 to 6 - reproductive class, from 6 to 10 - dominant self.pop.evolve( initOps=[ sim.InitSex(), # random genotype sim.InitGenotype(freq=[0.01]*2 + [0.03]*2 + [0.23]*4), # assign an unique ID to everyone. sim.IdTagger(), ], # increase the age of everyone by 1 before mating. preOps=[sim.InfoExec('age += 1'), sim.InfoExec("hc +=1 if 0 < hc < 3 else 0"), # Mother bear can't have cubs for two years after pregnancy sim.Migrator(rate=[[self.cro_to_slo]], mode=sim.BY_PROPORTION, subPops=[(0, 0)], toSubPops=[1]), # reproductive males migrate from Cro to Slo sim.Migrator(rate=[[self.slo_to_cro]], mode=sim.BY_PROPORTION, subPops=[(1, 0)], toSubPops=[0]), sim.Stat(effectiveSize=sim.ALL_AVAIL, subPops=[(0,1),(0,2),(0,4), (1,1), (1,2), (1,4)], vars='Ne_demo_base'), sim.Stat(effectiveSize=sim.ALL_AVAIL,subPops=[(0,1),(0,2),(0,4), (1,1), (1,2), (1,4)], vars='Ne_demo_base_sp') #sim.PyEval(r'"Cro %d, Slo %d' ' % (Cro, Slo)', "Cro = pop.subPopSize(0)" "Slo = pop.subPopSize(1)",exposePop='pop'), ], matingScheme=sim.HeteroMating([ # CloneMating will keep individual sex and all # information fields (by default). # The age of offspring will be zero. sim.HomoMating(subPops=sim.ALL_AVAIL, chooser=sim.CombinedParentsChooser( fatherChooser=sim.PyParentsChooser(generator=self.bearFather), motherChooser=sim.PyParentsChooser(generator=self.bearMother) ), generator=sim.OffspringGenerator(ops=[ sim.InfoExec("age = 0"), sim.IdTagger(), #sim.PedigreeTagger(), sim.ParentsTagger(), sim.MendelianGenoTransmitter() ], numOffspring=(sim.UNIFORM_DISTRIBUTION, 1, 3))), sim.CloneMating(subPops=[(0,0), (0,1), (0,2), (0,4), (1,0), (1,1), (1,2), (1,4)], weight=-1), ], subPopSize=popmodel.demoModel), # number of individuals? postOps = [ #sim.PyOperator(func=popmodel.NaturalMortality), sim.PyOperator(func = popmodel.CalcNe, param={"me":self.me, "Ne":self.Ne}, begin=int(0.2*self.generations)), sim.PyOperator(func = popmodel.CalcLDNe, param={"me":self.me, "x":self.x}, begin=int(0.2*self.generations)), sim.PyOperator(func=popmodel.cullCountry,param={"slo_cull": self.slo_cull, "cro_cull": self.cro_cull}), ], gen = self.generations )
def censuscontrol(gen): if gen >= 10 and gen < 13: return [10, 20] elif gen >= 13 and gen < 15: return [20, 40] elif gen == 15: return [22, 44] else: return [30, 60] pop = sim.Population( size=[8, 16], ploidy=2, loci=[0, 1, 2], infoFields=['ind_id', 'father_id', 'mother_id', 'gen_id', 'sp_id'], lociPos=(1, 2, 3), ancGen=gen_evolve) pop.evolve( initOps=[ sim.IdTagger(begin=0, end=-1), sim.InitSex(maleProp=0.5), sim.InitGenotype(freq=[0.2, 0.2, 0.2, 0.2, 0.2], loci=[0, 1, 2]), sim.PedigreeTagger(output='>>simp_Pedigree.ped', outputLoci=[0, 1, 2], outputFields=['gen_id', 'sp_id']) ], #end of initOps preOps=[ PyOperator(lambda pop: [ pop.setIndInfo(x, "sp_id", x) for x in range(pop.numSubPop())
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This script is an example in the simuPOP user's guide. Please refer to # the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim from simuPOP.utils import viewVars pop = sim.Population([1000, 2000], loci=3) sim.initGenotype(pop, freq=[0.2, 0.4, 0.4], loci=0) sim.initGenotype(pop, freq=[0.2, 0.8], loci=2) sim.stat(pop, genoFreq=[0, 1, 2], haploFreq=[0, 1, 2], alleleFreq=range(3), vars=['genoFreq', 'genoNum', 'haploFreq', 'alleleNum_sp']) viewVars(pop.vars())