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)
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)
Exemple #3
0
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
    )
Exemple #4
0
 def expand_by_selfing(self, pop, recombination_rates):
     """
     Specific for plant populations capable of selfing.
     Creates an F2 subpopulations generation by selfing the individuals of
     'pop'. Works on a population with one or more subpopulations.
     :param pop:
     """
     # self.odd_to_even(pop)
     num_sub_pops = pop.numSubPop()
     progeny_per_individual = int(self.operating_population_size / 2)
     return pop.evolve(
         preOps=[
             sim.MergeSubPops(),
             sim.PyEval(r'"Generation: %d\n" % gen'),
             sim.SplitSubPops(sizes=[1] * num_sub_pops, randomize=False),
         ],
         matingScheme=sim.SelfMating(
             subPopSize=[progeny_per_individual] * num_sub_pops,
             numOffspring=progeny_per_individual,
             ops=[
                 sim.Recombinator(rates=recombination_rates),
                 sim.IdTagger(),
                 sim.PedigreeTagger()
             ],
         ),
         gen=1,
     )
    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
Exemple #6
0
 def generate_f_one(self, pop: sim.Population):
     """
     A very basic implementation of the F_1 cross between pairs of individuals. Relies on
     pre-formatting of desired mating pairs into an ordered list.
     [1, 3, 5, 11, 12, 9, 22, 2]
     The mating pattern would be:
     1x3, 5x11, 12x9, 22x2. Rearranging the order of the indices would change the mating
     pairs.
     :param pop:
     :type pop:
     :return:
     :rtype:
     """
     pop.dvars().generations[1] = 'F_1'
     pop.dvars().gen = 1
     pairs_of_founders = int(pop.popSize() / 2)
     self.odd_to_even(pop)
     print("Creating the F_one population from selected founders.")
     return pop.evolve(
         preOps=[
             sim.PyEval(r'"Generation: %d\n" % gen'),
             operators.CalcTripletFrequencies(),
             sim.PyExec('triplet_freq[gen]=tripletFreq'),
             sim.SplitSubPops(sizes=[2] * pairs_of_founders, randomize=False),
         ],
         matingScheme=sim.RandomMating(subPopSize=[1] * pairs_of_founders,
                                       ops=[sim.Recombinator(rates=0.01), sim.IdTagger(), sim.PedigreeTagger()]),
         gen=1,
     )
Exemple #7
0
def execute(config, pop, mating_op):
    """Configure and run simulations."""

    _, init_genotype_op = cf.get_init_genotype_by_count(simu, 1)
    init_info_op = cf.get_init_info(simu)

    mutation_op = get_mutation_operator(m_rate=config.m,
                                        loci=config.loci,
                                        allele_length=config.allele_length,
                                        nrep=1,
                                        burnin=config.burnin)

    output_op = get_output_operator(config)

    simulator = simu.Simulator(pops=pop, rep=1)

    if config.debug > 0:
        post_op = [
            simu.Stat(alleleFreq=simu.ALL_AVAIL, step=config.debug),
            simu.PyEval(r"'%s\n' % alleleFreq", step=config.debug)
        ]
    else:
        post_op = []

    if config.output_per > 0:
        post_op.append(output_op)

    simulator.evolve(initOps=[init_info_op, init_genotype_op],
                     preOps=mutation_op,
                     matingScheme=mating_op,
                     postOps=post_op,
                     finalOps=output_op,
                     gen=config.gens + config.burnin)
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)
Exemple #9
0
    def recombinatorial_convergence(self, pop, recombination_rates):
        """
        Implements the MAGIC breeding scheme of breeding single individuals
        in pairs determined by the offspring of the initial population. The
        initial population is given by generate_f_one.
        :param pop:
        :type pop:
        :param recombination_rates:
        :type recombination_rates:
        :return:
        :rtype:
        """
        while pop.numSubPop() > 1:
            new_parents = list(pop.indInfo('ind_id'))
            new_parent_id_pairs = [(pid, pid + 1) for pid in new_parents[::2]]

            if len(new_parent_id_pairs) % 2 != 0 and \
                            len(new_parent_id_pairs) != 1:
                new_parent_id_pairs.append(random.choice(new_parent_id_pairs))

            new_os_size = len(new_parent_id_pairs)

            new_founder_chooser = breed.PairwiseIDChooser(new_parent_id_pairs)

            pop.evolve(
                preOps=[
                    sim.PyEval(r'"Generation: %d\t" % gen', ),
                    sim.Stat(popSize=True, numOfMales=True),
                    sim.PyEval(r'"popSize: %d\n" % popSize', ),
                ],
                matingScheme=sim.HomoMating(
                    sim.PyParentsChooser(new_founder_chooser.by_id_pairs),
                    sim.OffspringGenerator(ops=[
                        sim.IdTagger(),
                        sim.ParentsTagger(),
                        sim.PedigreeTagger(),
                        sim.Recombinator(rates=recombination_rates)
                    ],
                                           numOffspring=1),
                    subPopSize=new_os_size,
                ),
                gen=1,
            )
def execute(config, pop, mating_op):
    """
    Executes simulations with appropriate mutation model and mating scheme.
    """

    init = config.initial_genotype

    if init[0] == 'monomorphic':
        next_idx, init_genotype_op = cf.get_init_genotype_by_count(simu, 1)
    elif init[0] == 'unique':
        next_idx, init_genotype_op = cf.get_init_genotype_by_count(
            simu, 2 * config.N)
    elif init[0] == 'count':
        next_idx, init_genotype_op = cf.get_init_genotype_by_count(
            simu, init[1])
    elif init[0] == 'frequency':
        next_idx, init_genotype_op = get_init_genotype_by_prop(init[1])

    init_info_op = cf.get_init_info(simu)

    mutation_op = get_mutation_operator(m_rate=config.m,
                                        loci=config.loci,
                                        nrep=1,
                                        burnin=config.burnin,
                                        new_idx=next_idx)

    output_op = get_output_operator(config)

    simulator = simu.Simulator(pops=pop, rep=1)

    if config.debug > 0:
        post_op = [
            simu.Stat(alleleFreq=simu.ALL_AVAIL, step=config.debug),
            simu.PyEval(r"'%s\n' % alleleFreq", step=config.debug)
        ]
    else:
        post_op = []

    if config.output_per > 0:
        post_op.append(output_op)

    simulator.evolve(initOps=[init_info_op, init_genotype_op],
                     preOps=mutation_op,
                     matingScheme=mating_op,
                     postOps=post_op,
                     finalOps=output_op,
                     gen=config.gens + config.burnin)
    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)
Exemple #12
0
 def _mate_and_merge(self, pop: sim.Population):
     starting_gen = pop.vars()['gen']
     print("Initiating recombinatorial convergence at generation: %d" % pop.dvars().gen)
     while pop.numSubPop() > 1:
         pop.vars()['generations'][pop.vars()['gen']] = 'IG'+str(pop.vars()['gen'] - starting_gen)
         self.pop_halver(pop)
         self.odd_to_even(pop)
         self.pairwise_merge_protocol(pop)
         sub_pop_sizes = list(pop.subPopSizes())
         pop.evolve(
             preOps=[
                 sim.MergeSubPops(),
                 sim.PyEval(r'"Generation: %d\n" % gen'),
                 operators.CalcTripletFreq(),
                 sim.PyExec('triplet_freq[gen]=tripletFreq'),
                 sim.SplitSubPops(sizes=sub_pop_sizes, randomize=False),
             ],
             matingScheme=sim.RandomMating(ops=[sim.Recombinator(rates=0.01),
                                                sim.IdTagger(), sim.PedigreeTagger()]),
             gen=1,
         )
Exemple #13
0
 def interim_random_mating(self, pop, recombination_rates):
     """
     Randomly mates 'pop' for 'gens_of_random_mating' generations to further recombine founder genomes and dissolve
     population structure.
     :param pop: Founder population after mate_and_merge procedure
     :return: Population ready to be subjected to selection
     """
     print("Initiating interim random mating for {} generations.".format(
         self.generations_of_random_mating))
     pop.evolve(
         preOps=[
             sim.PyEval(r'"Generation: %d\n" % gen'),
         ],
         matingScheme=sim.RandomMating(
             subPopSize=self.operating_population_size,
             ops=[
                 sim.IdTagger(),
                 sim.PedigreeTagger(),
                 sim.Recombinator(rates=recombination_rates)
             ]),
         gen=self.generations_of_random_mating,
     )
Exemple #14
0
 def _generate_f_two(self, pop: sim.Population) -> sim.Population:
     """
     Creates an F2 subpopulations generation by selfing the individuals of 'pop'. Works on a population with one
     or more subpopulations.
     """
     pop.vars()['generations'][2] = 'F_2'
     self.odd_to_even(pop)
     num_sub_pops = pop.numSubPop()
     progeny_per_individual = int(self.selected_population_size/2)
     print("Creating the F_two population.")
     return pop.evolve(
         preOps=[
             sim.MergeSubPops(),
             sim.PyEval(r'"Generation: %d\n" % gen'),
             operators.CalcTripletFreq(),
             sim.PyExec('triplet_freq[gen]=tripletFreq'),
             sim.SplitSubPops(sizes=[1]*num_sub_pops, randomize=False),
         ],
         matingScheme=sim.SelfMating(subPopSize=[progeny_per_individual] * num_sub_pops,
                                     numOffspring=progeny_per_individual,
                                     ops=[sim.Recombinator(rates=0.01), sim.IdTagger(), sim.PedigreeTagger()],
                                     ),
         gen=1,
     )
Exemple #15
0
import simuPOP as sim
import random
pop = sim.Population(5000, loci=[3, 3])


def contextMut(allele, context):
    if context == [0, 0]:
        if allele == 0 and random.random() < 0.1:
            return 1
    elif context == [1, 1]:
        if allele == 0:
            return 1
    # do not mutate
    return allele


pop.evolve(
    # initialize locus by 0, 0, 0, 1, 0, 1
    initOps=[sim.InitSex(),
             sim.InitGenotype(genotype=[1, 1], loci=[3, 5])],
    preOps=[
        sim.PyMutator(func=contextMut, context=1, loci=[1, 4], rates=0.01),
        #sim.SNPMutator(u=0.01, v= 0.01, loci=[1, 4]),
        sim.Stat(alleleFreq=[1, 4], step=5),
        sim.PyEval(r"'Gen: %2d freq1: %.3f, freq2: %.3f\n'" +
                   " % (gen, alleleFreq[1][1], alleleFreq[4][1])",
                   step=5)
    ],
    matingScheme=sim.RandomMating(),
    gen=20)
Exemple #16
0
    #     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)
Exemple #17
0
# 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(1000, loci=[5]*4,
    # one autosome, two sex chromosomes, and one mitochondrial chromosomes
    chromTypes=[sim.AUTOSOME, sim.CHROMOSOME_X, sim.CHROMOSOME_Y, sim.MITOCHONDRIAL],
    infoFields=['fitness'])
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.25]*4)
    ],
    preOps=[
        sim.MapSelector(loci=17, fitness={(0,): 1, (1,): 1, (2,): 1, (3,): 0.4})
    ],
    matingScheme=sim.RandomMating(ops= [
        sim.Recombinator(rates=0.1),
        sim.MitochondrialGenoTransmitter(),
    ]),
    postOps=[
        sim.Stat(alleleFreq=17, step=10),
        sim.PyEval(r'"%.2f %.2f %.2f %.2f\n" % (alleleNum[17][0],'
            'alleleNum[17][1], alleleNum[17][2], alleleNum[17][3])', step=10),
    ],
    gen = 100
)

Exemple #18
0
    initOps=[
        sim.InitGenotype(
            freq=[startfreq, 1 -
                  startfreq]),  # initalize genotypes with, 2 alleles w/ freq
        sim.InitSex()
    ],
    # preOps=[                                             # do stuff before evolve
    #     sim.PyOutput('gen,freq\n', step=steps, output='>simtest_out.txt')
    # ],
    matingScheme=sim.HermaphroditicMating(
        sexMode=sim.NO_SEX
    ),  # the mating type can be changed, sexes, selfing etc
    postOps=[  # do stuff after evolve
        sim.Stat(alleleFreq=[0], begin=0, step=steps),  # calculate statistics
        sim.PyEval(r"'%d,%.2f\n' % (gen, alleleFreq[1][0])",
                   begin=0,
                   step=steps,
                   output='>>>simtest_out.txt'),
        # sim.PyOutput('\n', step=steps, output='>>simtest_out.txt')  # just puts newline in output
    ],
    # finalOps=sim.SavePopulation(output='sample.pop'),
    gen=gens)

sim.dump(pop)

print(open('simtest_out.txt').read())

df = pd.read_csv('simtest_out.txt')
df.head()

# genetic drift with 1 replication
pop = sim.Population(100, loci=5, chromNames=['chrom1'])
Exemple #19
0
# 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
simu = sim.Simulator(sim.Population(100, loci=[20]), 5)
simu.evolve(
    initOps=[sim.InitSex(), sim.InitGenotype(freq=[0.2, 0.8])],
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.Stat(alleleFreq=0, step=10),
        sim.PyEval('gen', step=10, reps=0),
        sim.PyEval(r"'\t%.2f' % alleleFreq[0][0]", step=10, reps=(0, 2, -1)),
        sim.PyOutput('\n', step=10, reps=-1)
    ],
    gen=30,
)
Exemple #20
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
pop = sim.Population(size=10000, ploidy=1, loci=[1, 1], infoFields='fitness')
pop.evolve(
    initOps=[sim.InitSex(), sim.InitGenotype(freq=[.5, .5])],
    # fitness values for AB, Ab, aB and ab
    preOps=sim.MaSelector(loci=[0, 1], fitness=[1, 1, 1, 0.95]),
    matingScheme=sim.RandomSelection(),
    postOps=[
        sim.Stat(haploFreq=[0, 1], step=25),
        sim.PyEval(
            r"'%.3f\t%.3f\t%.3f\t%.3f\n' % (haploFreq[(0,1)][(0,0)],"
            "haploFreq[(0,1)][(0,1)], haploFreq[(0,1)][(1,0)],"
            "haploFreq[(0,1)][(1,1)])",
            step=25)
    ],
    gen=100)
Exemple #21
0
# 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
pop = sim.Population(size=1000, loci=1, infoFields='fitness')
s1 = .1
s2 = .2
pop.evolve(initOps=[sim.InitSex(),
                    sim.InitGenotype(freq=[.2] * 5)],
           preOps=sim.MaSelector(loci=0, fitness=[1 - s1, 1, 1 - s2]),
           matingScheme=sim.RandomMating(),
           postOps=[
               sim.Stat(alleleFreq=0),
               sim.PyEval(r"'%.4f\n' % alleleFreq[0][0]", step=100)
           ],
           gen=301)
                                subPops=fitness.left_subpops,
                                output=">>" + selloci_file),
               sim.PyMlSelector(fitness.right,
                                subPops=fitness.right_subpops,
                                output=">>" + selloci_file),
           ],
           matingScheme=sim.RandomMating(ops=[
               id_tagger,
               sim.Recombinator(intensity=args.recomb_rate,
                                output=rc.collect_recombs,
                                infoFields="ind_id"),
           ]),
           postOps=[
               sim.Stat(numOfSegSites=sim.ALL_AVAIL, step=50),
               sim.PyEval(
                   r"'Gen: %2d #seg sites: %d\n' % (gen, numOfSegSites)",
                   step=50)
           ],
           gen=args.generations)

logfile.write("Done simulating!\n")
logfile.write(time.strftime('%X %x %Z') + "\n")
logfile.write("----------\n")
logfile.flush()

locations = [pop.subPopIndPair(x)[0] for x in range(pop.popSize())]
rc.add_diploid_samples(nsamples=args.nsamples,
                       sample_ids=pop.indInfo("ind_id"),
                       populations=locations)

del pop
Exemple #23
0
# 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 time
pop = sim.Population(1000, loci=10)
pop.dvars().init_time = time.time()
pop.dvars().last_time = time.time()
exec('import time', pop.vars(), pop.vars())
pop.evolve(
    initOps=sim.InitSex(),
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.IfElse('time.time() - last_time > 5', [
            sim.PyEval(r'"Gen: %d\n" % gen'),
            sim.PyExec('last_time = time.time()')
            ]),
        sim.TerminateIf('time.time() - init_time > 20')
    ]
)
        

Exemple #24
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
)

Exemple #25
0
# 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)
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0] * 4 + [0.1, 0.2, 0.3, 0.4])
    ],
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.KAlleleMutator(k=4,
                           rates=1e-4,
                           mapIn=[0] * 4 + list(range(4)),
                           mapOut=[4, 5, 6, 7]),
        sim.Stat(alleleFreq=0, step=100),
        sim.PyEval(
            r"', '.join(['%.2f' % alleleFreq[0][x] for x in range(8)]) + '\n'",
            step=100),
    ],
    gen=500)
Exemple #26
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
Exemple #27
0
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
)
Exemple #28
0
# 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(1000, loci=[20])
pop.evolve(
    initOps=[sim.InitSex(), sim.InitGenotype(freq=[0.8, 0.2])],
    preOps=[
        sim.PyEval(
            r"'At the beginning of gen %d: allele Freq: %.2f\n' % (gen, alleleFreq[0][0])",
            at=[-10, -1])
    ],
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.Stat(alleleFreq=0, begin=80, step=10),
        sim.PyEval(
            r"'At the end of gen %d: allele freq: %.2f\n' % (gen, alleleFreq[0][0])",
            begin=80,
            step=10),
        sim.PyEval(
            r"'At the end of gen %d: allele Freq: %.2f\n' % (gen, alleleFreq[0][0])",
            at=[-10, -1])
    ],
    finalOps=sim.SavePopulation(output='sample.pop'),
    gen=100)
Exemple #29
0
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)
import simuPOP as sim
pop = sim.Population(size=10000, loci=10, lociPos=range(5) + range(10, 15))
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(haplotypes=[[0]*10,[1]*10]),
    ],
    matingScheme=sim.RandomMating(ops=sim.Recombinator(intensity=0.0005)),
    postOps=[
        sim.Stat(LD=[[1,2],[4,5],[8,9],[0,9]], step=10),
        sim.PyEval(r"'gen=%d\tLD12=%.3f (%.3f)\tLD45=%.3f (%.3f)\tLD09=%.3f\n'%"
            "(gen, LD[1][2], 0.25*0.9995**(gen+1), LD[4][5],"
            "0.25*0.9975**(gen+1),LD[0][9])", step=10)
    ],
    gen=100
)