def createAge(pop):
    ageInitOps = [
        # InitInfo(lambda: random.randint(0, cfg.ages-2), infoFields='age'),
        sp.IdTagger(),
        # PyOperator(func=outputAge,at=[0]),
        sp.PyOperator(func=setAge, at=[0]),
    ]
    agePreOps = [
        sp.InfoExec("age += 1"),
        sp.InfoExec("mate = -1"),
        sp.InfoExec("force_skip = 0"),
        sp.PyOperator(func=outputAge),
    ]
    mySubPops = []
    for age in range(cfg.ages - 2):
        mySubPops.append((0, age + 1))
    mateOp = sp.HeteroMating([
        sp.HomoMating(
            sp.PyParentsChooser(fitnessGenerator if cfg.doNegBinom
                             else (litterSkipGenerator if cfg.Nb is None else
                                   restrictedGenerator)),
            sp.OffspringGenerator(numOffspring=1, ops=[
                sp.MendelianGenoTransmitter(), sp.IdTagger(),
                sp.PedigreeTagger()],
                sexMode=(sp.PROB_OF_MALES, cfg.maleProb)), weight=1),
        sp.CloneMating(subPops=mySubPops, weight=-1)],
        subPopSize=calcDemo)
    agePostOps = [
        sp.PyOperator(func=outputMega),
        sp.PyOperator(func=cull),
    ]
    pop.setVirtualSplitter(sp.InfoSplitter(field='age',
                                           cutoff=list(range(1, cfg.ages))))
    return ageInitOps, agePreOps, mateOp, agePostOps
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
 def replicate_tuson_drift_simulation(self, pop, meta_population,
                                      meta_sample_size,
                                      recombination_rates):
     for replicate in pop.populations():
         replicate.dvars().gen = 0
     female_chooser = sim.RandomParentChooser(
         selectionField='female_fitness')
     male_chooser = sim.RandomParentChooser(selectionField='male_fitness')
     print("Beginning simulation of genetic drift with parameters:")
     breeding_params = {
         'n_breeding_females': self.number_of_breeding_females,
         'n_breeding_males': self.number_of_breeding_males,
         'sample_sizes': meta_sample_size}
     print("Breeding females: {n_breeding_females}, breeding males: "
           "{n_breeding_males}, "
           "sample sizes: {sample_sizes}".format(**breeding_params))
     return pop.evolve(
         initOps=[
             operators.ReplicateMetaPopulation(meta_population,
                                               meta_sample_size),
             sim.PyEval(
                 r'"Initial: Sampled %d individuals from generation %d Replicate: %d.\n" % (ss, gen_sampled_from, rep)'),
         ],
         preOps=[
             sim.PyEval(r'"Generation: %d\n" % gen'),
             sim.InfoExec('generation=gen'),
             operators.ReplicateMetaPopulation(meta_population,
                                               meta_sample_size,
                                               at=[2, 4, 6, 8]),
             # Evaluation specifying the generations should be the same as the evaluation at every generation.
             sim.PyEval(
                 r'"Sampled %d individuals from generation %d from replicate: %d.\n" % (ss, gen_sampled_from, rep)',
                 at=[2, 4, 6, 8]),
             operators.RandomlyAssignFemaleFitness(
                 self.number_of_breeding_females),
             operators.RandomlyAssignMaleFitness(
                 self.number_of_breeding_males),
         ],
         matingScheme=sim.HomoMating(
             sim.CombinedParentsChooser(female_chooser, male_chooser,
                                        allowSelfing=True),
             sim.OffspringGenerator(ops=[
                 sim.ParentsTagger(),
                 sim.IdTagger(),
                 sim.PedigreeTagger(),
                 sim.Recombinator(rates=recombination_rates)],
             ),
         ),
         finalOps=[
             sim.InfoExec('generation=gen'),
             operators.ReplicateMetaPopulation(meta_population,
                                               meta_sample_size),
             sim.PyEval(
                 r'"Final: Sampled %d individuals from generation %d\n" % (ss, gen_sampled_from)')
         ],
         gen=self.number_of_generations)
Exemplo n.º 4
0
    def expansion_through_random_mating(self, pop, expanded_pop_size,
                                        recombination_rates):

        # The purpose of this function is to use the simuPOP pre-defined mating scheme
        # RandomMating to grow the population to an arbitrary size.
        # Self-pollination occurs frequently in maize so we need use HermaphroditicMating
        # instead of RandomMating.
        return pop.evolve(
            initOps=sim.InitSex(),
            preOps=[
                sim.PyEval(r'"Generation: %d\n" % gen'),
                sim.InfoExec('generation=gen'),
            ],
            matingScheme=sim.HermaphroditicMating(
                ops=[sim.Recombinator(rates=recombination_rates),
                     sim.IdTagger(),
                     sim.PedigreeTagger()],
                subPopSize=expanded_pop_size),
            gen=1)
Exemplo n.º 5
0
 def population_structure_guided_expansion(self, pop, recombination_rates):
     """
     Uses a population structure matrix to determine the probability of
     selecting a second parent given the first parent's probability mass
     function.
     """
     ps_pc = breed.ForcedPopulationStructureParentChooser(
         self.population_size)
     print(
         "Executing population expansion using estimated population structure.")
     return pop.evolve(
         initOps=sim.InitSex(),
         preOps=[
             sim.InfoExec('generation=gen'),
         ],
         matingScheme=sim.HomoMating(
             sim.PyParentsChooser(ps_pc.forced_structure_parent_chooser),
             sim.OffspringGenerator(ops=[
                 sim.IdTagger(),
                 sim.PedigreeTagger(),
                 sim.Recombinator(rates=recombination_rates),
             ]),
             subPopSize=self.population_size),
         gen=1)
Exemplo n.º 6
0
    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.
        sim.RandomMating(ops=[
            sim.IdTagger(),                   # give new born an ID
            sim.PedigreeTagger(),             # track parents of each individual
            sim.MendelianGenoTransmitter(),   # transmit genotype
        ],
        numOffspring=(sim.UNIFORM_DISTRIBUTION, 1, 3),
        subPops=[(0,1)]),],
        subPopSize=demoModel),
Exemplo n.º 7
0
def runSimulation(scenario_id, sub_population_size, minMatingAge, maxMatingAge,
                  gen):
    '''
    sub_population_size   A vector giving the population sizes for each sub-population. The subpopulations determine which breeding ground an individual belongs to
    minMatingAge          minimal mating age.
    maxMatingAge          maximal mating age. Individuals older than this are effectively dead
    years                 number of years to simulate
    '''

    # scenario_id describes the batch of files to load
    # The mitochondrial DNA will be in mtdna_<scenario_id>
    # The SNP DNA will be in snp_<scenario_id>

    # Read the mitochondrial haplotype frequencies. There's a bit to unpack here
    # We read the lines into an array, and for each one, call split() on it to get one element per column.
    # However, we do not want this - we want the transpose, where haplotype_frequencies[0] is a vector of
    # all the frequencies for population 0, and haplotype_frequencies[1] is the corresponding vector for
    # population 2. list(map(list, zip(*t))) will achieve this transformation for us.
    # While we are at it, we also convert the strings into floats.
    mitochondrial_file = "mtdna_" + scenario_id + ".txt"
    with open(mitochondrial_file, "r") as fd:
        haplotype_frequencies = list(
            map(list,
                zip(*[list(map(float, line[0:-1].split())) for line in fd])))

    if len(haplotype_frequencies) != len(sub_population_size):
        raise ValueError(
            'The number of populations in the population size vector and the number of populations deduced from the haplotype file are different'
        )

    # Now read the SNP data. This builds a 2D array indexed as snp[locus][population]
    snp_file = "snp_" + scenario_id + ".txt"
    with open(snp_file, "r") as fd:
        snp = [list(map(float, line[0:-1].split())) for line in fd]

    sub_population_count = len(sub_population_size)
    print()
    print(sub_population_count, "subpopulations detected")

    # Now we can create the population. We want to give each population a population name, starting from A
    sub_population_names = list(map(chr, range(65, 65 + sub_population_count)))

    # We have two chromosomes. The first is an autosome with nb_loci loci, and the second is the mitochondrial chromosome with 1 locus
    pop = simuPOP.Population(
        sub_population_size,
        ploidy=2,
        loci=[nb_loci, 1],
        ancGen=2,
        infoFields=[
            'age', 'ind_id', 'father_id', 'mother_id', 'nitrogen', 'carbon',
            'feeding_ground', 'native_breeding_ground', 'migrate_to'
        ],
        subPopNames=sub_population_names,
        chromTypes=[simuPOP.AUTOSOME, simuPOP.MITOCHONDRIAL])
    sub_population_names = tuple(sub_population_names)

    # Create an attribute on each individual called 'age'. Set it to a random number between 0 and maxMatingAge
    # Note that size is a vector - the size of each population. We have to sum these to get the total number of individuals
    individual_count = sum(sub_population_size)

    # Assign a random age to each individual
    pop.setIndInfo(
        [random.randint(0, maxMatingAge) for x in range(individual_count)],
        'age')
    # Assign a random feeding ground to each individual
    pop.setIndInfo([
        random.randint(0, numberOfFeedingGrounds - 1)
        for x in range(individual_count)
    ], 'feeding_ground')

    # Currently we have these virtual subpopulations:
    # age < minMatingAge (juvenile)
    # age >= minMatingAge and age < maxMatingAge + 0.1 (age <= maxMatingAge) (mature)
    # age >= maxMatingAge (dead)
    #
    # Ideally we would want something like this:
    # 1) Immature
    # 2) Receptive female (every 3 years)
    # 3) Non-receptive female
    # 4) Mature male
    # 5) Dead
    #
    # Note that we use a cutoff InfoSplitter here, it is also possible to
    # provide a list of values, each corresponding to a virtual subpopulation.
    pop.setVirtualSplitter(
        simuPOP.CombinedSplitter([
            simuPOP.ProductSplitter([
                simuPOP.SexSplitter(),
                simuPOP.InfoSplitter('age',
                                     cutoff=[minMatingAge, maxMatingAge + 0.1],
                                     names=['juvenile', 'mature', 'dead'])
            ])
        ],
                                 vspMap=[[0], [1], [2], [3], [4], [5],
                                         [0, 1, 3, 4], [1, 4]],
                                 names=[
                                     'Juvenile Male', 'Mature Male',
                                     'Dead Male', 'Juvenile Female',
                                     'Mature Female', 'Dead Female',
                                     'Not dead yet', 'Active'
                                 ]))

    pop.evolve(
        initOps=[
            simuPOP.InitSex(),
            simuPOP.IdTagger(),
            simuPOP.PyOperator(func=init_native_breeding_grounds)
        ] + [
            simuPOP.InitGenotype(subPops=sub_population_names[i],
                                 freq=haplotype_frequencies[i],
                                 loci=[nb_loci])
            for i in range(0, sub_population_count)
        ] + [
            simuPOP.InitGenotype(subPops=sub_population_names[i],
                                 freq=[snp[n][i], 1 - snp[n][i]],
                                 loci=[n])
            for i in range(0, sub_population_count)
            for n in range(0, nb_loci - 1)
        ],
        # increase age by 1
        preOps=[simuPOP.InfoExec('age += 1')],
        matingScheme=simuPOP.HeteroMating(
            [
                # age <= maxAge, copy to the next generation (weight=-1)
                # subPops is a list of tuples that will participate in mating. The tuple is a pair (subPopulation, virtualSubPopulation)
                # First, we propagate (clone) all individuals in all subpopulations (and all VSPs except the ones who are now in the VSP of deceased individuals) to the next generation
                simuPOP.CloneMating(
                    ops=[simuPOP.CloneGenoTransmitter(chroms=[0, 1])],
                    subPops=[
                        (sub_population, 6)
                        for sub_population in range(0, sub_population_count)
                    ],
                    weight=-1),
                # Then we simulate random mating only in VSP 1 (ie reproductively mature individuals) within subpopulation (breeding/winter grounds)
                simuPOP.RandomMating(
                    ops=[
                        simuPOP.MitochondrialGenoTransmitter(),
                        simuPOP.MendelianGenoTransmitter(),
                        simuPOP.IdTagger(),
                        simuPOP.InheritTagger(mode=simuPOP.MATERNAL,
                                              infoFields=['feeding_ground']),
                        simuPOP.InheritTagger(
                            mode=simuPOP.MATERNAL,
                            infoFields=['native_breeding_ground']),
                        simuPOP.PedigreeTagger()
                    ],
                    subPops=[
                        (sub_population, 7)
                        for sub_population in range(0, sub_population_count)
                    ],
                    weight=1)
            ],
            subPopSize=configure_new_population_size),
        postOps=[

            # Determine the isotopic ratios in individuals
            simuPOP.PyOperator(func=postop_processing),
            simuPOP.Migrator(mode=simuPOP.BY_IND_INFO),
            # count the individuals in each virtual subpopulation
            #simuPOP.Stat(popSize=True, subPops=[(0,0), (0,1), (0,2), (1,0), (1, 1), (1, 2)]),
            # print virtual subpopulation sizes (there is no individual with age > maxAge after mating)
            #simuPOP.PyEval(r"'Size of age groups: %s\n' % (','.join(['%d' % x for x in subPopSize]))")

            # Alternatively, calculate the Fst
            # FIXME: How does this actually work? Does it work for > 2 populations? I don't really understand it yet
            # ELC: it is a calculation that partitions variance among and between populations, and can be calculated as a
            # global statistic or on a pairwise basis. We use it as an indication of genetic differentiation.
            simuPOP.Stat(structure=range(1),
                         subPops=sub_population_names,
                         suffix='_AB',
                         step=10),
            simuPOP.PyEval(r"'Fst=%.3f \n' % (F_st_AB)", step=10)
        ],
        gen=years)

    #simuPOP.dump(pop, width=3, loci=[], subPops=[(simuPOP.ALL_AVAIL, simuPOP.ALL_AVAIL)], max=1000, structure=False);
    #return

    ped = simuPOP.Pedigree(pop)
    print("This is the pedigree stuff")
    simuPOP.dump(pop)

    # Now sample the individuals
    sample = drawRandomSample(pop, sizes=[sample_count] * sub_population_count)

    # Print out the allele frequency data
    simuPOP.stat(sample, alleleFreq=simuPOP.ALL_AVAIL)
    frequencies = sample.dvars().alleleFreq
    with open('freq.txt', 'w') as freqfile:
        index = 0
        for locus in frequencies:
            if (locus == nb_loci):
                continue
            if (len(frequencies[locus]) < 2):
                continue
            print(index, end=' ', file=freqfile)
            index = index + 1
            for allele in frequencies[locus]:
                print(frequencies[locus][allele], end=' ', file=freqfile)
            print(file=freqfile)

    # We want to remove monoallelic loci. This means a position in the genotype for which all individuals have the same value in both alleles
    # To implement this we will build up a list of loci that get ignored when we dump out the file. Generally speaking, if we add all the values up
    # then either they will sum to 0 (if all individuals have type 0) or to the number of individuals * 2 (if all individuals have type 1)
    geno_sum = [0] * (nb_loci + 1) * 2
    for individual in sample.individuals():
        geno_sum = list(map(add, geno_sum, individual.genotype()))
    final_sum = list(
        map(add, geno_sum[:(nb_loci + 1)], geno_sum[(nb_loci + 1):]))

    monoallelic_loci = []
    for i in range(0, nb_loci):
        if final_sum[i] == 0 or final_sum[
                i] == sample_count * sub_population_count * 2:
            monoallelic_loci = [i] + monoallelic_loci
    monoallelic_loci = sorted(monoallelic_loci, reverse=True)

    nb_ignored_loci = len(monoallelic_loci)
    # Generate the two files
    with open('mixfile.txt', 'w') as mixfile:
        with open('haploiso.txt', 'w') as haplofile:
            print(sub_population_count,
                  nb_loci - nb_ignored_loci,
                  2,
                  1,
                  file=mixfile)
            print("sex, haplotype, iso1, iso2, native_ground", file=haplofile)
            for i in range(0, nb_loci - nb_ignored_loci):
                print('Loc', i + 1, sep='_', file=mixfile)
            for individual in sample.individuals():
                genotype = individual.genotype()
                print(
                    1 if individual.sex() == 1 else 0,
                    genotype[nb_loci],
                    individual.info('carbon'),
                    individual.info('nitrogen'),
                    #                      int(individual.info('native_breeding_ground')),
                    file=haplofile,
                    sep=' ')
                print(int(individual.info('native_breeding_ground') + 1),
                      end=' ',
                      file=mixfile)
                for i in range(0, nb_loci):
                    if i not in monoallelic_loci:
                        print(genotype[i] + 1,
                              genotype[i + nb_loci + 1] + 1,
                              ' ',
                              end='',
                              sep='',
                              file=mixfile)
                print(file=mixfile)
    return sample
Exemplo n.º 8
0
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 = [
      sim.Stat(popSize=True, subPops=[(0,0), (0,1), (0,2)]),
      sim.PyExec("Surviving['larvae'].append(subPopSize[0])"),
      sim.PyExec("Surviving['adults'].append(subPopSize[1])"),
      sim.PyExec("Surviving['smurfs'].append(subPopSize[2])"),
Exemplo n.º 9
0
# 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
pop = sim.Population(size=2000, loci=1, infoFields='fitness')
pop.evolve(initOps=[sim.InitSex(),
                    sim.InitGenotype(freq=[.5, .5])],
           preOps=[
               sim.MaPenetrance(loci=0, penetrance=[0.01, 0.1, 0.2]),
               sim.Stat(numOfAffected=True, step=25, vars='propOfAffected'),
               sim.PyEval(r"'Percent of affected: %.3f\t' % propOfAffected",
                          step=50),
               sim.InfoExec('fitness = not ind.affected()', exposeInd='ind')
           ],
           matingScheme=sim.RandomMating(),
           postOps=[
               sim.Stat(alleleFreq=0),
               sim.PyEval(r"'%.4f\n' % alleleFreq[0][1]", step=50)
           ],
           gen=151)
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
        sz = 80, 550
    else:
        sz = min(150, 80 * 1.05**(gen - 120)), 550
    print(
        f"{gen} young/adult/old sp0 : {pop.subPopSize([0, 'age < 3'])} /{pop.subPopSize([0, '3 <= age < 9'])} / {pop.subPopSize([0, '9 <= age < 17'])}"
        +
        f" sp1 : {pop.subPopSize([1, 'age < 3'])} / {pop.subPopSize([1, '3 <= age < 9'])} / {pop.subPopSize([1, '9 <= age < 17'])}"
    )
    return sz


pop1 = pop.clone()
pop1.evolve(
    preOps=[
        migr,
        sim.InfoExec('age += 1'),
    ],
    matingScheme=sim.HeteroMating(
        [
            # only adult individuals with age >=3 will mate and produce
            # offspring. The age of offspring will be zero.
            sim.RandomMating(ops=[
                sim.MendelianGenoTransmitter(),
                sim.Recombinator(intensity=0.1)
            ],
                             subPops=[(sim.ALL_AVAIL, '3 <= age < 9'),
                                      (sim.ALL_AVAIL, '9 <= age < 17')],
                             weight=-0.1),
            # individuals with age < 17 will be kept, but might be removed due to
            # population size decline
            sim.CloneMating(subPops=[(
Exemplo n.º 12
0
###############################################################
#                         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'],
                           outputLoci=[0]),
        sim.PyExec(
            "AccumAges = {1: {0: {x: 0 for x in range(maxAge)}, 1: {x: 0 for x in range(maxAge)}, 2: {x: 0 for x in range(maxAge)}}, 2: {0: {x: 0 for x in range (maxAge)}, 1: {x: 0 for x in range(maxAge)}, 2: {x: 0 for x in range(maxAge)}}}"
        )
    ],
Exemplo n.º 13
0
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
Exemplo n.º 14
0
 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
     ) 
Exemplo n.º 15
0
    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)
Exemplo n.º 16
0
# 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
pop = sim.Population(size=2000, loci=1, infoFields='fitness')
pop.evolve(initOps=[sim.InitSex(),
                    sim.InitGenotype(freq=[.5, .5])],
           preOps=[
               sim.Stat(alleleFreq=0),
               sim.InfoExec('''fitness = {
            0: 1,
            1: 1 - (alleleFreq[0][1] - 0.5)*0.1, 
            2: 1 - (alleleFreq[0][1] - 0.5)*0.2}[ind.allele(0,0)+ind.allele(0,1)]''',
                            exposeInd='ind'),
               sim.Stat(meanOfInfo='fitness'),
               sim.PyEval(
                   r"'alleleFreq=%.3f, mean fitness=%.5f\n' % (alleleFreq[0][1], meanOfInfo['fitness'])",
                   step=25),
           ],
           matingScheme=sim.RandomMating(),
           gen=151)
Exemplo n.º 17
0
                #
                # genotype
                #
                geno = ind.genotype()
                output.write(' '.join([format_string % (geno[x], geno[numLoci + x]) for x in range(numLoci)]) +
                        f'\t{"M" if ind.sex() == sim.MALE else "F"}\t{ind.age}\t{ind.fitness}\n')
        return True



pop1 = pop.clone()
pop1.addInfoFields('fitness')
pop1.evolve(
    preOps=[
        migr,
        sim.InfoExec('age += 1'),
        sim.InfoExec('fitness = (50 - ind.age)/50', exposeInd='ind'),
    ],
    matingScheme=sim.HeteroMating([
        # only adult individuals with age >=3 will mate and produce
        # offspring. The age of offspring will be zero.
        sim.RandomMating(ops=[
            sim.MendelianGenoTransmitter()],
            subPops=[(sim.ALL_AVAIL,'3 <= age < 17')],
            weight=-0.1),
        # individuals with age < 17 will be kept, but might be removed due to
        # population size decline
        sim.CloneMating(subPops=[(sim.ALL_AVAIL, 'age < 3'), (sim.ALL_AVAIL, '3 <= age < 17')]),
        ],
        subPopSize=demoModel),
    postOps=[
Exemplo n.º 18
0
#

import simuPOP as sim
pop = sim.Population(1000, loci=[1], infoFields=['aff', 'numOfAff'])
# define virtual subpopulations by affection sim.status
pop.setVirtualSplitter(sim.AffectionSplitter())
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.5, 0.5]),
    ],
    preOps=[
        # get affection sim.status for parents
        sim.MaPenetrance(loci=0, wildtype=0, penetrance=[0.1, 0.2, 0.4]),
        # set 'aff' of parents
        sim.InfoExec('aff = ind.affected()', exposeInd='ind'),
    ],
    # get number of affected parents for each offspring and store in numOfAff
    matingScheme=sim.RandomMating(ops=[
        sim.MendelianGenoTransmitter(),
        sim.SummaryTagger(mode=sim.SUMMATION, infoFields=['aff', 'numOfAff'])
    ]),
    postOps=[
        # get affection sim.status for offspring
        sim.MaPenetrance(loci=0, wildtype=0, penetrance=[0.1, 0.2, 0.4]),
        # calculate mean 'numOfAff' of offspring, for unaffected and affected subpopulations.
        sim.Stat(meanOfInfo='numOfAff',
                 subPops=[(0, 0), (0, 1)],
                 vars=['meanOfInfo_sp']),
        # print mean number of affected parents for unaffected and affected offspring.
        sim.PyEval(
Exemplo n.º 19
0
###############################################################
#                         SIMULATION                          #
###############################################################

simu = sim.Simulator(pop, rep=1)

simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.9, 0.1]),
        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.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()
    ],
    # The order should be: becoming a smurf or not since previous day, dying or not, aging one day
    # if lucky enough, and then mate at that age.
    preOps=[
        sim.InfoExec("luck = random.random()"),
        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.DiscardIf(natural_death),
        sim.InfoExec("age += 1")
    ],
Exemplo n.º 20
0
exec("import random\nrandom.seed(seed)", pop.vars(), pop.vars())
exec("import math", pop.vars(), pop.vars())

###############################################################
#                         SIMULATION                          #
###############################################################

simu = sim.Simulator(pop, rep=1)

simu.evolve(
   initOps = [
      sim.InitSex(),
      sim.InitGenotype(freq = [0.5, 0.5]),
      sim.InitInfo([0], infoFields = 'age'),
      sim.InitInfo([1], infoFields = 'fitness'),
      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()
   ],
   preOps = [
      sim.InfoExec("luck = random.random()"),
      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.DiscardIf(natural_death),
      sim.InfoExec("age += 1"),
      sim.PySelector(loci=[0], func=fitness_func)
   ],
   matingScheme = sim.HeteroMating(
      [
Exemplo n.º 21
0
        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())
        ] is not None),
    ],
    matingScheme=sim.MonogamousMating(
        subPopSize=censuscontrol,
        numOffspring=8,
        sexMode=(sim.NUM_OF_MALES, 2),
        ops=[
            sim.InfoExec('gen_id = gen'),
            sim.MendelianGenoTransmitter(),
            sim.IdTagger(),
            sim.InheritTagger(infoFields='sp_id'),
            sim.PedigreeTagger(output='>>simp_Pedigree.ped',
                               outputLoci=[0, 1, 2],
                               outputFields=['gen_id', 'sp_id']),
        ],  #end of Ops
    ),  #end of matingScheme   
    gen=gen_evolve,
)  #end of pop.evolve
#Pedigree plus info sent to the monitor
print "ind_id, Sire, Dam, Sex, Affection, gen_id, sp_id, Loc1a,Loc1b, Loc2a,Loc2b, Loc3a, Loc3b,"
print(open('simp_Pedigree.ped').read())
Exemplo n.º 22
0
    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)