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
Esempio n. 2
0
    def generate_f_one(self, parental_id_pairs, offspring_per_pair):
        """
        Crosses pairs of founders as they are listed in founder indices.
        using breed.PairwiseIDChooser

        :note: Data is specified as pairs. Testing for even-number unnecessary.
        """

        founder_chooser = PairwiseIDChooser(parental_id_pairs,
                                            offspring_per_pair)
        number_of_pairs = len(parental_id_pairs)
        self.pop.evolve(
            preOps=[
                #                sim.PyEval(r'"Generation: %d\n" % gen',),
            ],
            matingScheme=sim.HomoMating(
                sim.PyParentsChooser(founder_chooser.by_id_pairs),
                sim.OffspringGenerator(ops=[
                    sim.IdTagger(),
                    sim.PedigreeTagger(),
                    sim.Recombinator(rates=self.recombination_rates)
                ],
                                       numOffspring=1),
                subPopSize=[offspring_per_pair * number_of_pairs],
            ),
            gen=1,
        )
Esempio n. 3
0
def get_pure_hermaphrodite_mating(r_rate,
                                  weight,
                                  size,
                                  loci,
                                  allele_length,
                                  field='self_gen'):
    """
    Construct mating scheme for pure hermaphrodite with partial selfing under the
    infinite sites model.

    A fraction, 0 <= weight <= 1, of offspring is generated by selfing, and others are
    generated by outcrossing.  In this model, there is no specific sex so that any
    individual can mate with any other individuals in a population.
    Furthermore, a parent can participate in both selfing and outcrossing.
    """
    field = str(field)
    # Index of sites, after which recombinations happen.
    rec_loci = [allele_length * i - 1 for i in range(1, loci + 1)]
    selfing = simu.SelfMating(ops=[
        simu.Recombinator(rates=r_rate, loci=rec_loci),
        cf.MySelfingTagger(field)
    ],
                              weight=weight)

    outcross = simu.HomoMating(
        chooser=simu.PyParentsChooser(generator=cf.pickTwoParents),
        generator=simu.OffspringGenerator(ops=[
            simu.Recombinator(rates=r_rate, loci=rec_loci),
            cf.MyOutcrossingTagger(field)
        ]),
        weight=1.0 - weight)

    return simu.HeteroMating(matingSchemes=[selfing, outcross],
                             subPopSize=size)
 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)
Esempio n. 5
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,
            )
Esempio n. 6
0
    def recombinatorial_convergence(self, multi_replicate_populations,
                                    number_sub_populations,
                                    offspring_per_pair):
        """
        Breeds individuals from different sub-populations together until a
        single hybrid sub-population is created.
        :note:`number_sub_populations*offspring_per_pair should equal operating_population_size.`
        :note:`For the time being only works with powers of 2.`


        :param sim.Simulator multi_replicate_populations:
        :param int number_sub_populations:
        :param int offspring_per_pair:
        :return:
        """
        print("Start of recombinatorial convergence.")
        while number_sub_populations > 1:
            mrc = MultiRandomCross(multi_replicate_populations,
                                   number_sub_populations, offspring_per_pair)
            mothers, fathers = mrc.determine_random_cross()
            multi_snd_order_chooser = MultiSecondOrderPairIDChooser(
                mothers, fathers)
            print("Prior to convergence: {}".format(number_sub_populations))
            multi_replicate_populations.evolve(
                matingScheme=sim.HomoMating(
                    sim.PyParentsChooser(
                        multi_snd_order_chooser.snd_ord_id_pairs),
                    sim.OffspringGenerator(ops=[
                        sim.IdTagger(),
                        sim.PedigreeTagger(),
                        sim.Recombinator(rates=self.recombination_rates)
                    ],
                                           numOffspring=1),
                    subPopSize=[
                        int(number_sub_populations * offspring_per_pair)
                    ]),
                gen=1,
            )
            number_sub_populations = int(number_sub_populations / 2)
            offspring_per_pair = int(2 * offspring_per_pair)
        self._convergence = True
 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)
Esempio n. 8
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)
Esempio n. 9
0
                     infoFields=['pod'],
                     chromTypes=[sim.AUTOSOME, sim.CUSTOMIZED])
pop.setVirtualSplitter(sim.InfoSplitter('pod', values=range(5)))
pop.evolve(
    initOps=[
        sim.InitSex(),
        # assign individuals to a random pod
        sim.InitInfo(lambda: randint(0, 4), infoFields='pod'),
        # only the first pod has the disease alleles
        sim.InitGenotype(freq=[0.8, 0.2], subPops=[(0, 0)]),
    ],
    matingScheme=sim.HomoMating(
        sim.PyParentsChooser(podParentsChooser),
        sim.OffspringGenerator(
            numOffspring=1,
            ops=[
                sim.MendelianGenoTransmitter(),
                sim.MitochondrialGenoTransmitter(),
                # offspring stays with their natal pod
                sim.InheritTagger(mode=sim.MATERNAL, infoFields='pod')
            ])),
    postOps=[
        # calulate allele frequency at each pod
        sim.Stat(alleleFreq=(0, 1),
                 vars='alleleFreq_sp',
                 subPops=[(0, sim.ALL_AVAIL)]),
        sim.PyEval(
            r"'Loc0: %s Loc1: %s\n' % ("
            "', '.join(['%.3f' % subPop[(0,x)]['alleleFreq'][0][1] for x in range(5)]),"
            "', '.join(['%.3f' % subPop[(0,x)]['alleleFreq'][1][1] for x in range(5)]))"
        ),
    ],
Esempio n. 10
0
founder_chooser = breed.PairwiseIDChooser(founders, offspring_per_pair)
number_of_pairs = len(founders)
example_pop.evolve(
    initOps=[
        sim.InitLineage(
            mode=sim.FROM_INFO
        ),  #assigns lineage of each allele to be tracked through pop.evolve
    ],
    preOps=[],
    matingScheme=sim.HomoMating(
        sim.PyParentsChooser(founder_chooser.by_id_pairs),
        sim.OffspringGenerator(
            ops=[
                sim.IdTagger(),
                sim.PedigreeTagger(output='>>pedigree0.ped'
                                   ),  #outputs pedigree file for checking
                sim.Recombinator(rates=recom_map)
            ],
            numOffspring=1),
        subPopSize=[offspring_per_pair * number_of_pairs],
    ),
    gen=1,
)

### Generate Double Hybrids
#Define mothers and fathers, this case is 3 crosses between each pair of hybrid
mothers = np.array([8., 8., 8., 10., 10., 10.])
fathers = np.array([9., 9., 9., 11., 11., 11.])
second_order_chooser = breed.SecondOrderPairIDChooser(
    mothers, fathers
)  #Defines parental pairs, 8 mated with 9 three times,10 mated with 11 three times
pop = sim.Population(100000, loci=[1] * 40, infoFields=['A', 'B', 'I', 'D'])
pop.evolve(
    initOps=[
        sim.InitSex(maleProp=0.5),
        sim.InitGenotype(freq=[0.5, 0.5]),
    ],
    preOps=[
        sim.PyQuanTrait(func=traits,
                        loci=sim.ALL_AVAIL,
                        infoFields=['A', 'B', 'I', 'D']),
        sim.PyOperator(func=lambda pop: pop.sortIndividuals('D') is None),
    ],
    matingScheme=sim.HomoMating(chooser=sim.SequentialParentsChooser(),
                                generator=sim.OffspringGenerator(
                                    ops=sim.MendelianGenoTransmitter(),
                                    numOffspring=2,
                                    sexMode=(sim.NUM_OF_MALES, 1))),
    finalOps=sim.PyQuanTrait(func=traits,
                             loci=sim.ALL_AVAIL,
                             infoFields=['A', 'B', 'I', 'D']),
    gen=10)

from rpy import r


def genoTraitCorrelation(loc, trait):
    'Calculate correlation between trait and genotype at a locus'
    geno = [
        ind.allele(loc, 0) + ind.allele(loc, 1) for ind in pop.individuals()
    ]
Esempio n. 12
0
def test_generate_operating_population():

    genetic_map = pd.read_csv('nam_prefounders_genetic_map.txt', index_col=None,
                             sep='\t')

    pf_map = shelve.open('pf_map')
    misc_gmap = shelve.open('misc_gmap')
    uniparams = shelve.open('uniparams')

    locus_names = uniparams['locus_names']
    pos_column = uniparams['pos_column']
    allele_names = uniparams['allele_names']
    snp_to_integer = uniparams['snp_to_integer']
    integer_to_snp = uniparams['integer_to_snp']

    alleles = misc_gmap['alleles']
    chr_cM_positions = misc_gmap['chr_cM_positions']
    cM_positions = misc_gmap['cM_positions']
    integral_valued_loci = misc_gmap['integral_valued_loci']
    relative_integral_valued_loci = misc_gmap['relative_integral_valued_loci']
    recombination_rates = misc_gmap['recombination_rates']

    nam = sim.loadPopulation(uniparams['prefounder_file_name'])
    sim.tagID(nam, reset=True)
    nam.setSubPopName('maize_nam_prefounders', 0)

    selection_statistics = {
        'aggregate': {},
        'selected': {},
        'non-selected': {}
    }

    ind_names_for_gwas = {i: {} for i in range(uniparams[
        'number_of_replicates'])}
    uniparams['meta_pop_sample_sizes'] = {i: 100 for i in
                                          range(0, uniparams['generations_of_selection'] + 1, 2)
                                          }

    s = simulate.Truncation(uniparams['generations_of_selection'],
                           uniparams['generations_of_random_mating'],
                           uniparams['operating_population_size'],
                            uniparams[
                                'proportion_of_individuals_saved'],
                           uniparams['overshoot_as_proportion'],
                       uniparams['individuals_per_breeding_subpop'],
                           uniparams['heritability'],
                           uniparams['meta_pop_sample_sizes'],
                           uniparams['number_of_replicates'])

    ind_names_for_gwas = {i: {} for i in range(uniparams[
        'number_of_replicates'])}

    founders = uniparams['founders']
    replicated_nam = sim.Simulator(nam, rep=2, stealPops=False)
    pop = replicated_nam.extract(0)

    assert pop.popSize() == 26, "Population is too large."

    s.generate_f_one(pop, recombination_rates, founders, 100)

    assert pop.popSize() == 400, "Population should have size: {} after the F_1 mating " \
                                               "procedure." \
                                               "".format(len(founders) * 100)

    #pop.splitSubPop(0, [100] * 4)
    #subpop_list = list(range(pop.numSubPop()))

    intmd_os_struct = s.restructure_offspring(pop, 100, 4)
    snd_order = breed.SecondOrderPairIDChooser(intmd_os_struct, 1)

    pop.evolve(
        preOps=[sim.MergeSubPops()],
        matingScheme=sim.HomoMating(
            sim.PyParentsChooser(snd_order.snd_ord_id_pairs),
            sim.OffspringGenerator(ops=[
                sim.IdTagger(),
                sim.ParentsTagger(),
                sim.PedigreeTagger(),
                sim.Recombinator(rates=recombination_rates)
            ],
                numOffspring=1),
            subPopSize=[200],
        ),
        gen=1,
    )

    assert pop.popSize() == 1, "Population does not have correct size after second round of mating."

    second_intmd_os_struct = s.restructure_offspring(pop, 100, 2)
    third_order = breed.SecondOrderPairIDChooser(second_intmd_os_struct, 1)


    pop.evolve(
        preOps=[sim.MergeSubPops()],
        matingScheme=sim.HomoMating(
            sim.PyParentsChooser(third_order.snd_ord_id_pairs),
            sim.OffspringGenerator(ops=[
                sim.IdTagger(),
                sim.ParentsTagger(),
                sim.PedigreeTagger(),
                sim.Recombinator(rates=recombination_rates)
            ],
                numOffspring=1),
            subPopSize=[100],
        ),
        gen=1,
    )

    assert pop.popSize() == 100, "Second merge of breeding sub-populations. Offspring population does not have " \
                                 "correct size"
Esempio n. 13
0
    import random
    class myParentsChooser:
        def __init__(self, maleIndexes, femaleIndexes):
            self.maleIndexes = maleIndexes
            self.femaleIndexes = femaleIndexes
        def chooseParents(self):
            return self.maleIndexes[random.randint(0, len(self.maleIndexes)-1)],\
                self.femaleIndexes[random.randint(0, len(self.femaleIndexes)-1)]

def parentsChooser(pop, sp):
    'How to call a C++ level parents chooser.'
    # create an object with needed information (such as x, y) ...
    pc = myParentsChooser(
        [x for x in range(pop.popSize()) if pop.individual(x).sex() == sim.MALE],
        [x for x in range(pop.popSize()) if pop.individual(x).sex() == sim.FEMALE])
    while True:
        # return indexes of parents repeatedly
        yield pc.chooseParents()

pop = sim.Population(100, loci=1)
simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.5, 0.5])
    ],
    matingScheme=sim.HomoMating(sim.PyParentsChooser(parentsChooser),
        sim.OffspringGenerator(ops=sim.MendelianGenoTransmitter())),
    gen = 100
)

Esempio n. 14
0
def do_forward_sims(sim_data, chrom_len, diploid_Ne, batchname, repilcates,
                    simupop_seed):
    print("start getting chromosomes positions")
    chromosome_positions = get_chromosome_positions(sim_data=sim_data,
                                                    chromsome_length=chrom_len)
    print("done getting chromosomes positions")

    haplotypes = get_haplotypes(sim_data)
    loci_per_chromsome = get_loci_per_chromosome(chromosome_positions)
    n_chrom = len(loci_per_chromsome)
    # set up the ancestral pop in simuPOP
    initial = simuPOP.Population(
        diploid_Ne,  # here is the diploid number
        loci=
        loci_per_chromsome,  # should be the number of loci on each chromosome
        lociPos=list(chromosome_positions),
        ploidy=2,
        infoFields=['father_idx', 'mother_idx', 'ind_id'],
        #alleleNames=['A', 'C', 'G', 'T'],
        lociNames=[
            'locus_{}'.format(x) for x in xrange(len(chromosome_positions))
        ])
    simuPOP.initGenotype(initial,
                         prop=[1.0 / len(haplotypes)] * len(haplotypes),
                         haplotypes=list(haplotypes))
    simuPOP.tagID(initial, reset=1)
    initial_export = get_export_genotypes(initial, initial.popSize())
    np.savetxt('./share/{}/Ne-{}_Chr-{}/Ne-{}_Chr-{}.inital.txt'.format(
        batchname, diploid_Ne, n_chrom, diploid_Ne, n_chrom),
               initial_export,
               delimiter='\t',
               fmt='%01d')

    # map-ped
    simuPOP.utils.export(
        initial,
        format='PED',
        output='./share/{}/Ne-{}_Chr-{}/Ne-{}_Chr-{}.inital.ped'.format(
            batchname, diploid_Ne, n_chrom, diploid_Ne, n_chrom),
        gui=False,
        idField='ind_id')
    simuPOP.utils.export(
        initial,
        format='MAP',
        output='./share/{}/Ne-{}_Chr-{}/Ne-{}_Chr-{}.inital.map'.format(
            batchname, diploid_Ne, n_chrom, diploid_Ne, n_chrom),
        gui=False)

    # Doesn't yet work!!
    # set the seed for simuPOP
    #simuPOP.setRNG(seed=simupop_seed)
    # and in Python
    #random.seed(simupop_seed)
    # and for numpy
    #np.random.seed(simupop_seed)

    print("initalizing the forward simulator")
    simu = simuPOP.Simulator(
        simuPOP.Population(
            diploid_Ne,  # here is the diploid number
            loci=get_loci_per_chromosome(
                chromosome_positions
            ),  # should be the number of loci on each chromosome
            lociPos=list(chromosome_positions),
            ploidy=2,
            infoFields=['ind_id', 'father_idx', 'mother_idx'],
            #alleleNames=['A', 'C', 'G', 'T'],
            lociNames=[
                'locus_{}'.format(x) for x in xrange(len(chromosome_positions))
            ]),
        rep=repilcates)

    print("Start evolving {} replicates".format(repilcates))
    simu.evolve(
        initOps=[
            simuPOP.InitSex(
                sex=[simuPOP.MALE, simuPOP.FEMALE]),  # alternate sex
            simuPOP.InitGenotype(prop=[1.0 / len(haplotypes)] *
                                 len(haplotypes),
                                 haplotypes=list(haplotypes))
        ],
        matingScheme=simuPOP.HomoMating(
            chooser=simuPOP.PyParentsChooser(fixedChooser),
            generator=simuPOP.OffspringGenerator(
                sexMode=(simuPOP.GLOBAL_SEQUENCE_OF_SEX, simuPOP.MALE,
                         simuPOP.FEMALE),
                ops=[
                    simuPOP.Recombinator(intensity=1.0 / chrom_len),
                    simuPOP.ParentsTagger()
                ]),
        ),
        postOps=[],
        gen=20)

    print("Done evolving {} replicates!".format(repilcates))

    # export the data
    print("Exporting data!".format(repilcates))
    for rep, pop in enumerate(simu.populations()):
        if diploid_Ne >= 200:
            pop_genotypes = get_export_genotypes(pop,
                                                 n_ind=200)  #  select 200 inds
        else:
            pop_genotypes = get_export_genotypes(
                pop, n_ind=diploid_Ne)  #  select 200 inds

        np.savetxt('./share/{}/Ne-{}_Chr-{}/Ne-{}_Chr-{}_Frep-{}.geno'.format(
            batchname, diploid_Ne, n_chrom, diploid_Ne, n_chrom,
            rep).format(rep),
                   pop_genotypes,
                   delimiter='\t',
                   fmt='%01d')
        if rep % 10 == 0:
            print "saved rep {}".format(rep)
Esempio n. 15
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)
Esempio n. 16
0
        females.append([x for x in pop.individuals(subPop) \
            if x.sex() == sim.FEMALE and x.rank == rank])
    #
    while True:
        # choose a rank randomly
        rank = int(
            pop.individual(randint(0,
                                   pop.subPopSize(subPop) - 1), subPop).rank)
        yield males[rank][randint(0, len(males[rank]) - 1)], \
            females[rank][randint(0, len(females[rank]) - 1)]


def setRank(rank):
    'The rank of offspring can increase or drop to zero randomly'
    # only use rank of the father
    return (rank[0] + randint(-1, 1)) % 3


pop = sim.Population(size=[1000, 2000], loci=1, infoFields='rank')
pop.evolve(initOps=[
    sim.InitSex(),
    sim.InitInfo(lambda: randint(0, 2), infoFields='rank')
],
           matingScheme=sim.HomoMating(
               sim.PyParentsChooser(randomChooser),
               sim.OffspringGenerator(ops=[
                   sim.MendelianGenoTransmitter(),
                   sim.PyTagger(setRank),
               ])),
           gen=5)
Esempio n. 17
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# This script is an example in the simuPOP user's guide. Please refer to
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed
# description of this example.
#

import simuPOP as sim
pop = sim.Population(100, loci=5 * 3, infoFields='parent_idx')
pop.evolve(initOps=[sim.InitGenotype(freq=[0.2] * 5)],
           preOps=sim.Dumper(structure=False, max=5),
           matingScheme=sim.HomoMating(
               sim.SequentialParentChooser(),
               sim.OffspringGenerator(ops=[
                   sim.SelfingGenoTransmitter(),
                   sim.ParentsTagger(infoFields='parent_idx'),
               ])),
           postOps=sim.Dumper(structure=False, max=5),
           gen=1)
Esempio n. 18
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
def traj(gen):
    return [0.5 + gen * 0.01]

pop = sim.Population(1000, loci=[10]*2)
# evolve the sim.Population while keeping allele frequency 0.5
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.5, 0.5])
    ],
    matingScheme=sim.HomoMating(sim.RandomParentChooser(),
        sim.ControlledOffspringGenerator(loci=5,
            alleles=[0], freqFunc=traj,
            ops = sim.SelfingGenoTransmitter())),
    postOps=[
        sim.Stat(alleleFreq=[5, 15]),
        sim.PyEval(r'"%.2f\t%.2f\n" % (alleleFreq[5][0], alleleFreq[15][0])')
    ],
    gen = 5
)

Esempio n. 19
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
     ) 
Esempio n. 20
0
def simuAssortativeMatingWithFitness(e):
    '''
        Accepts:
        e               an Experiment object.

        Returns a dict containing the results from each gen of the simulation:
        gen             generation number.
        A               frequency of the A allele.
        a               frequency of the a allele.
        AA              frequency of AA individuals.
        Aa              frequency of Aa individuals.
        aa              frequency of aa individuals.
        deaf            frequency of deaf individuals (incl adventitious).
        AA_size         size of the AA subpopulation.
        Aa_size         size of the Aa subpopulation.
        aa_size         size of the aa subpopulation.
        deaf_size       size of the deaf subpopulation (incl adventitious).
        homogamy        calculated actual homogamy.
        F               calculated inbreeding coefficient.

        Adopted from: http://simupop.sourceforge.net/Cookbook/AssortativeMating
    '''
    sim.setRNG(random.seed(sim.getRNG().seed()))
    pop = sim.Population(e.constant_pop_size * 1000, loci=[1])
    # These variables need to be set in order to be available to customChooser().
    # There appears to be no way to directly pass variables to customChooser().
    pop.dvars().constant_pop_size = e.constant_pop_size
    pop.dvars().a = e.a
    pop.dvars().aa_fitness = e.aa_fitness
    pop.dvars().aa_homogamy = e.aa_homogamy
    pop.dvars().deaf = e.deaf
    pop.dvars().adv_deaf_target = int(
        round((e.deaf - e.a**2) * e.constant_pop_size * 1000))

    # These will hold the final data
    pop.dvars().headers = []
    pop.dvars().row = []
    pop.evolve(
        initOps= [sim.InitGenotype(freq=[1-e.a, e.a])],
        matingScheme = sim.HomoMating(
                    chooser = sim.PyParentsChooser(customChooser),
                    generator = sim.OffspringGenerator(sim.MendelianGenoTransmitter())),
        postOps = [sim.Stat(alleleFreq=[0], genoFreq=[0]),
                   sim.PyExec(r"headers += ['gen','A', 'a',"\
                               "'AA', 'Aa', 'aa', 'deaf', 'AA_size', 'Aa_size', " \
                               "'aa_size',  'deaf_size', 'homogamy', 'F'] \n" \
                               "F = 1.0-((genoFreq[0][(0,1)]+genoFreq[0][(1,0)])/" # F          \
                               "(2.0*alleleFreq[0][0]*alleleFreq[0][1])) "\
                               "if alleleFreq[0][0]*alleleFreq[0][1] > 0. "\
                               "else 0. \n" \
                               "deaf_size = min(genoNum[0][(1,1)] + adv_deaf_target, constant_pop_size*1000) \n"\
                               "row += [gen, "                           # generation \
                               "alleleFreq[0][0], "                      # A          \
                               "alleleFreq[0][1], "                      # a          \
                               "genoFreq[0][(0,0)],"                     # AA         \
                               "genoFreq[0][(0,1)]+genoFreq[0][(1,0)], " # Aa         \
                               "genoFreq[0][(1,1)], "                    # aa         \
                               "deaf_size/(constant_pop_size*1000.), "   # deaf       \
                               "genoNum[0][(0,0)], "                     # AA_size    \
                               "genoNum[0][(0,1)]+genoNum[0][(1,0)], "   # Aa_size    \
                               "genoNum[0][(1,1)], "                     # aa_size    \
                               "deaf_size, "                             # deaf_size  \
                               "homogamy, "                              # homogamy   \
                               "F if F>0. else 0.]")                     # F          \
                   ],
        gen = e.generations
    )
    return {'headers': pop.dvars().headers, 'row': pop.dvars().row}