def initialize_meta_population(self, pop, number_of_reps=1):
     if number_of_reps == 1:
         sim_meta = sim.Simulator(pop, rep=1, stealPops=False)
         meta_pop = sim_meta.extract(0)
         meta_pop.removeSubPops(0)
         return meta_pop
     else:
         proto_meta = pop.clone()
         proto_meta.setSubPopName('meta', 0)
         proto_meta.removeSubPops(0)
         sim_meta = sim.Simulator(proto_meta, rep=number_of_reps,
                                  stealPops=False)
     return sim_meta
Beispiel #2
0
 def prepare_sim(self, params):
     for view in self._views:
         for info in view.info_fields:
             self._info_fields.add(info)
     if params['num_snps'] > 0:
         pop, init_ops, pre_ops, post_ops = \
             self._create_island([params['pop_size']] * params['num_pops'],
                                 params['mig'], params['num_snps'])
         loci, genome_init = self._create_snp_genome(
             params['num_snps'], freq=params['snp_freq'])
         gpre_ops = []
     else:
         pop, init_ops, pre_ops, post_ops = \
             self._create_island([params['pop_size']] * params['num_pops'],
                                 params['mig'], params['num_msats'])
         loci, genome_init, gpre_ops = self._create_genome(
             params['num_msats'],
             start_alleles=params['num_msat_alleles'])
     view_ops = []
     for view in self._views:
         view.pop = pop
         view_ops.extend(view.view_ops)
     for view in self._views:
         post_ops.append(sp.PyOperator(func=_hook_view, param=view))
     post_ops = view_ops + post_ops
     sim = sp.Simulator(pop, 1, True)
     return {'sim': sim, 'pop': pop, 'init_ops': init_ops + genome_init,
             'pre_ops': pre_ops, 'post_ops': post_ops,
             'mating_scheme': sp.RandomMating()}
Beispiel #3
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 setUp(self):
     self.pop = simu.Population(size=10, loci=1, infoFields='self_gen')
     self.sim = simu.Simulator(pops=self.pop)
     self.initOps = [
         simu.InitSex(sex=[simu.MALE, simu.FEMALE]),
         simu.InitInfo(0, infoFields=['self_gen'])
     ]
     self.sexMode = (simu.GLOBAL_SEQUENCE_OF_SEX, simu.MALE, simu.FEMALE)
 def setUp(self):
     # A locus with 10 sites
     "Let there are 5 loci with 2 sites each"
     self.allele_length = 2
     self.loci = 5
     self.pop = simu.Population(size=10,
                                loci=self.allele_length * self.loci,
                                infoFields='self_gen')
     self.sim = simu.Simulator(pops=self.pop)
     self.initOps = [
         simu.InitSex(sex=[simu.MALE, simu.FEMALE]),
         simu.InitInfo(0, infoFields=['self_gen'])
     ]
     self.sexMode = (simu.GLOBAL_SEQUENCE_OF_SEX, simu.MALE, simu.FEMALE)
def 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)
Beispiel #7
0
 def prepare_sim(self, params):
     for view in self._views:
         for info in view.info_fields:
             self._info_fields.add(info)
     nloci = 1 + params['neutral_loci']
     pop, init_ops, pre_ops, post_ops = \
         self._create_single_pop(params['pop_size'], nloci)
     view_ops = []
     for view in self._views:
         view.pop = pop
         view_ops.extend(view.view_ops)
     for view in self._views:
         post_ops.append(sp.PyOperator(func=_hook_view, param=view))
     post_ops = view_ops + post_ops
     loci, genome_init = self._create_snp_genome(
         nloci, freq=params['snp_freq'])
     sim = sp.Simulator(pop, 1, True)
     if params['sel_type'] == 'hz_advantage':
         ms = sp.MapSelector(loci=0, fitness={
             (0, 0): 1 - params['sel'],
             (0, 1): 1,
             (1, 1): 1 - params['sel']})
     elif params['sel_type'] == 'recessive':
         ms = sp.MapSelector(loci=0, fitness={
             (0, 0): 1 - params['sel'],
             (0, 1): 1 - params['sel'],
             (1, 1): 1})
     else:  # dominant
         ms = sp.MapSelector(loci=0, fitness={
             (0, 0): 1 - params['sel'],
             (0, 1): 1,
             (1, 1): 1})
     return {'sim': sim, 'pop': pop, 'init_ops': init_ops + genome_init,
             'pre_ops': pre_ops, 'post_ops': post_ops,
             'mating_scheme': sp.RandomMating(
                 ops=[sp.MendelianGenoTransmitter(), ms])}
Beispiel #8
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
simu = sim.Simulator(sim.Population(size=1000, loci=2), rep=3)
simu.evolve(initOps=[sim.InitSex(),
                     sim.InitGenotype(genotype=[1, 2, 2, 1])],
            matingScheme=sim.RandomMating(ops=sim.Recombinator(rates=0.01)),
            postOps=[
                sim.Stat(LD=[0, 1]),
                sim.PyEval(r"'%.2f\t' % LD[0][1]", step=20, output='>>LD.txt'),
                sim.PyOutput('\n', reps=-1, step=20, output='>>LD.txt'),
                sim.PyEval(r"'%.2f\t' % R2[0][1]", output='R2.txt'),
                sim.PyEval(r"'%.2f\t' % LD[0][1]",
                           step=20,
                           output="!'>>LD_%d.txt' % rep"),
            ],
            gen=100)
print(open('LD.txt').read())
print(open('R2.txt').read())  # Only the last write operation succeed.
Beispiel #9
0
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

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

import simuPOP as sim

simu = sim.Simulator(sim.Population(10000, loci=[100] * 5), rep=2)
simu.evolve(initOps=[sim.InitSex(),
                     sim.InitGenotype(freq=[0.1, 0.9])],
            matingScheme=sim.RandomMating(),
            postOps=[
                sim.Stat(alleleFreq=0),
                sim.TicToc(step=50, reps=-1),
            ],
            gen=101)
import simuOpt
simuOpt.setOptions(quiet=True, alleleType='long')
import simuPOP as sim
pop = sim.Population(size=1000, loci=[1])
simu = sim.Simulator(pop, 10)
simu.evolve(
    initOps=[sim.InitSex(),
             sim.PointMutator(loci=0, allele=1, inds=0)],
    matingScheme=sim.RandomMating(),
    finalOps=sim.Stat(alleleFreq=0),
    gen=100)
print([x.dvars().alleleNum[0][1] for x in simu.populations()])
Beispiel #11
0
    args.popsize, args.mutationrate)
log.info("Starting data collection at generation: %s", beginCollectingData)

totalSimulationLength = beginCollectingData + args.length
log.info("Simulation will sample %s generations after stationarity",
         args.length)

data.storeSimulationData(args.popsize, args.mutationrate, sim_id,
                         args.samplesize, args.replications, args.numloci,
                         __file__, args.numloci, simconfig.MAXALLELES)

initial_distribution = utils.constructUniformAllelicDistribution(args.numloci)
log.info("Initial allelic distribution: %s", initial_distribution)

pop = sim.Population(size=args.popsize, ploidy=1, loci=args.numloci)
simu = sim.Simulator(pop, rep=args.replications)

simu.evolve(
    initOps=sim.InitGenotype(freq=initial_distribution),
    preOps=[
        sim.PyOperator(func=utils.logGenerationCount,
                       param=(),
                       step=1000,
                       reps=0),
    ],
    matingScheme=sim.RandomSelection(),
    postOps=[
        sim.KAlleleMutator(k=simconfig.MAXALLELES,
                           rates=args.mutationrate,
                           loci=sim.ALL_AVAIL),
        sim.PyOperator(func=data.sampleNumAlleles,
    'founder_population_filename': founder_filename,
    'simulated_pop_size': popsize,
    'number_breeding_males': males,
    'number_breeding_females': females,
    'number_generations': generations,
    'number_of_reps': replicates,
    'sample_sizes': experimental_meta_population_sample_size,
}

with open('simulation_parameters.json', 'w') as simparams:
    json.dump(sim_params, simparams, indent=5)

for batch in range(92, 101):
    print("Executing batch: {batch_id}.".format(batch_id=batch))
    subpops_and_gens = [(1, 0), (2, 2), (3, 4), (4, 6), (5, 8), (6, 10)]
    tuson_replicates = sim.Simulator(tuson, rep=replicates, stealPops=False)
    tuson_meta_replicates = td.initialize_meta_population(tuson,
                                                          number_of_reps=replicates)
    td.replicate_tuson_drift_simulation(tuson_replicates,
                                        tuson_meta_replicates,
                                        experimental_meta_population_sample_size,
                                        recom_rates)
    print("Multi-replicate drift simulation complete.")
    allelefrequencies = td.insert_allele_frequencies_into_aggregate_matrix(
        replicates, tuson_meta_replicates,
        minor_alleles)
    np.savetxt('batch_' + str(batch) + '_af.txt', allelefrequencies,
               fmt='%.3f', delimiter='\t')
    homofrequencies, heterofrequencies = td.insert_minor_genotype_frequencies_into_aggregate_matrix(
        minor_homozygotes_by_locus,
        minor_heterozygotes_by_locus,
Beispiel #13
0
#NOTE THAT THIS OUTCOME WILL BE DIFFERENT EVERY TIME YOU RUN THE SIMULATION

simulation_outcome = {}

#Define sampling rate:
for sampling in [36, 48, 60, 72, 84]:

    #Define the population
    pop = sim.Population(size=100, loci=1)

    #Define the demographic trajectory
    demo_function = serf.demo_dynamic(101, 100., np.log(2), 100000., 10., 30,
                                      sampling)

    #Initiate the simulation
    simu = sim.Simulator(pop, rep=100)

    #Evolve population
    simu.evolve(
        initOps=[
            sim.InitSex(),
            sim.InitGenotype(
                freq=[0.95, 0.05]),  #proportion of minor to major allele
            sim.PyExec(
                'traj=[]')  #Initiate a recipient list for frequency outputs
        ],
        matingScheme=sim.RandomSelection(
            subPopSize=demo_function),  #random binary fission
        postOps=[
            sim.Stat(alleleFreq=0),
            sim.PyExec('traj.append(alleleFreq[0][1])',
Beispiel #14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--experiment",
                        help="provide name for experiment",
                        required=True,
                        type=str,
                        default="test")
    parser.add_argument("--debug", help="turn on debugging output")
    parser.add_argument("--reps",
                        help="Replicated populations per parameter set",
                        type=int,
                        default=1)
    parser.add_argument(
        "--networkfile",
        help=
        "Name of GML file representing the  network model for this simulation",
        required=True,
        type=str)
    parser.add_argument("--numloci",
                        help="Number of loci per individual",
                        type=int,
                        required=True)
    parser.add_argument(
        "--maxinittraits",
        help="Max initial number of traits per locus for initialization",
        type=int,
        required=True)
    parser.add_argument(
        "--innovrate",
        help=
        "Rate at which innovations occur in population as a per-locus rate",
        type=float,
        default=0.001)
    parser.add_argument(
        "--simlength",
        help=
        "Time at which simulation and sampling end, defaults to 3000 generations",
        type=int,
        default="20")
    parser.add_argument(
        "--popsize",
        help="Initial size of population for each community in the model",
        type=int,
        required=True)
    parser.add_argument(
        "--migrationfraction",
        nargs='+',
        help="Fraction of population that migrates each time step",
        type=float,
        required=True,
        default=[])
    parser.add_argument(
        "--seed",
        type=int,
        help="Seed for random generators to ensure replicability")
    parser.add_argument("--k_values",
                        nargs='+',
                        type=int,
                        help="list of k-values to explore [e.g., 2 4 20 24",
                        default=[])
    parser.add_argument("--sub_pops",
                        nargs='+',
                        help="Number of sub populations",
                        required=True,
                        default=[10])
    parser.add_argument("--maxalleles",
                        type=int,
                        help="Maximum number of alleles",
                        default=50)
    parser.add_argument("--save_figs",
                        type=bool,
                        help="Save figures or not?",
                        default=True)
    parser.add_argument("--burnintime",
                        type=int,
                        help="How long to wait before making measurements? ",
                        default=2000)
    parser.add_argument("--rewiringprob",
                        type=float,
                        help="Probability of random rewiring",
                        default=0)

    config = parser.parse_args()

    # check the k and migration rate combinations
    for kvalue in config.k_values:
        if float(kvalue) * float(config.migrationfraction) >= 1.0:
            print("k=%s * mig=%4f is greater than 1.0\n" %
                  (kvalue, config.migrationfraction))
            print(
                "Please adjust input values for k and/or migration rate and restart.\n "
            )
        sys.exit()

    # setup output directories for writing
    output_path = utils.setup_output(config.experiment)

    # save parameters
    utils.save_parameters(str(sys.argv), config, output_path)

    k_run_values = config.k_values
    subpop_run_values = config.sub_pops

    ## make sure the k values are less than # of subpops and > 1
    for k in k_run_values:
        for subnum in subpop_run_values:
            if int(k) > int(subnum) or int(k) < 2:
                print(
                    "k values can not be greater than the number of sub populations. k = %s subpops = %s \n"
                    % (k, subnum))
                sys.exit()

    ## initialize the output dictionary
    for k in k_run_values:
        for sb in subpop_run_values:
            output[k][sb] = {}

    # set up the frequencies for the alleles in each loci. Here assuming a uniform distribution as a starting point
    distribution = utils.constructUniformAllelicDistribution(
        config.maxinittraits)

    iteration_number = -1
    for k in k_run_values:
        for subnum in subpop_run_values:
            iteration_number += 1
            ## these are lists of things that simuPop will do at different stages
            init_ops = OrderedDict()
            pre_ops = OrderedDict()
            post_ops = OrderedDict()

            # Construct a demographic model from a collection of network slices which represent a temporal network
            # of changing subpopulations and interaction strengths.  This object is Callable, and simply is handed
            # to the mating function which applies it during the copying process
            #networkmodel = NetworkModel( networkmodel="/Users/clipo/Documents/PycharmProjects/RapaNuiSim/notebooks/test_graph.gml",
            networkmodel = network.NetworkModel(
                networkmodel="smallworld",
                simulation_id=config.experiment,
                sim_length=config.simlength,
                burn_in_time=config.burnintime,
                initial_subpop_size=config.popsize,
                migrationfraction=config.migrationfraction,
                sub_pops=subnum,
                connectedness=k,  # if 0, then distance decay
                save_figs=config.save_figs,
                network_iteration=iteration_number)

            num_pops = networkmodel.get_subpopulation_number()
            sub_pop_size = int(config.popsize / num_pops)

            # The regional network model defines both of these, in order to configure an initial population for evolution
            # Construct the initial population
            pops = sp.Population(
                size=[sub_pop_size] * num_pops,
                subPopNames=str(list(networkmodel.get_subpopulation_names())),
                infoFields='migrate_to',
                ploidy=1,
                loci=config.numloci)

            ### now set up the activities
            init_ops['acumulators'] = sp.PyOperator(
                utils.init_acumulators,
                param=['fst', 'alleleFreq', 'haploFreq'])
            init_ops['Sex'] = sp.InitSex()

            init_ops['Freq'] = sp.InitGenotype(loci=list(range(
                config.numloci)),
                                               freq=distribution)

            post_ops['Innovate'] = sp.KAlleleMutator(k=config.maxalleles,
                                                     rates=config.innovrate,
                                                     loci=sp.ALL_AVAIL)
            post_ops['mig'] = sp.Migrator(
                rate=networkmodel.get_migration_matrix())  #, reps=[3])
            #for i, mig in enumerate(migs):
            #        post_ops['mig-%d' % i] = sp.Migrator(demography.migrIslandRates(mig, num_pops), reps=[i])

            post_ops['Stat-fst'] = sp.Stat(structure=sp.ALL_AVAIL)

            post_ops['Stat-richness'] = sp.Stat(
                alleleFreq=[0],
                haploFreq=[0],
                vars=['alleleFreq', 'haploFreq', 'alleleNum', 'genoNum'])
            post_ops['fst_acumulation'] = sp.PyOperator(
                utils.update_acumulator, param=['fst', 'F_st'])
            post_ops['richness_acumulation'] = sp.PyOperator(
                utils.update_richness_acumulator,
                param=('alleleFreq', 'Freq of Alleles'))
            post_ops['class_richness'] = sp.PyOperator(
                utils.calculateAlleleAndGenotypeFrequencies,
                param=(config.popsize, config.numloci))

            mating_scheme = sp.RandomSelection()
            #mating_scheme=sp.RandomSelection(subPopSize=sub_pop_size)

            ## go simuPop go! evolve your way to the future!
            sim = sp.Simulator(pops, rep=config.reps)
            print("now evolving... k = %s with sub_pops = %s" % (k, subnum))
            sim.evolve(initOps=list(init_ops.values()),
                       preOps=list(pre_ops.values()),
                       postOps=list(post_ops.values()),
                       matingScheme=mating_scheme,
                       gen=config.simlength)

            # now make a figure of the Fst results
            fig = plt.figure(figsize=(16, 9))
            ax = fig.add_subplot(111)
            count = 0
            for pop in sim.populations():
                ax.plot(pop.dvars().fst, label='Replicate: %s' % count)
                output[k][subnum][count] = deepcopy(pop.dvars())
                count += 1
            ax.legend(loc=2)
            ax.set_ylabel('FST')
            ax.set_xlabel('Generation')
            plt.show()

    sum_fig = plt.figure(figsize=(16, 9))
    ax = sum_fig.add_subplot(111)
    iteration = -1
    for k in k_run_values:
        for subnum in subpop_run_values:
            iteration += 1
            # only label the first one
            for n in range(config.reps):
                if n == 0:
                    ax.plot(output[k][subnum][n].fst,
                            color=list(
                                dict(mcolors.BASE_COLORS,
                                     **mcolors.CSS4_COLORS).keys())[iteration],
                            label='k = %s subpops = %s' % (k, subnum))
                else:
                    ax.plot(output[k][subnum][n].fst,
                            color=list(
                                dict(mcolors.BASE_COLORS,
                                     **mcolors.CSS4_COLORS).keys())[iteration])
    ax.legend(loc=2)
    ax.set_ylabel('Fst')
    ax.set_xlabel('Generations')
    plt.show()
    savefilename = output_path + "/sum_fig.png"
    sum_fig.savefig(savefilename, bbox_inches='tight')

    rich_fig = plt.figure(figsize=(16, 9))
    ax = rich_fig.add_subplot(111)
    iteration = -1
    for k in k_run_values:
        for sb in subpop_run_values:
            iteration += 1
            # only add a label for the first one (not all the replicates)
            for n in range(config.reps):
                if n == 0:
                    ax.plot(output[k][subnum][n].richness,
                            color=list(
                                dict(mcolors.BASE_COLORS,
                                     **mcolors.CSS4_COLORS).keys())[iteration],
                            label='k = %s subpops = %s' % (k, subnum))
                else:
                    ax.plot(output[k][subnum][n].richness,
                            color=list(
                                dict(mcolors.BASE_COLORS,
                                     **mcolors.CSS4_COLORS).keys())[iteration])
    ax.legend(loc=2)
    ax.set_ylabel('Richness')
    ax.set_xlabel('Generations')
    plt.show()
    savefilename = output_path + "/richness.png"
    rich_fig.savefig(savefilename, bbox_inches='tight')

    ## output CI for the parameters

    summary_fig = plt.figure(figsize=(16, 9))
    ax = summary_fig.add_subplot(111)

    iteration = -1
    for k in k_run_values:
        for subnum in subpop_run_values:
            iteration += 1
            CI_average = []
            CI_min = []
            CI_max = []
            for t in range(len(output[k][subnum][0].fst)):
                point_in_time = []
                for n in range(config.reps):
                    list_of_points = list(output[k][subnum][n].fst)
                    point_in_time.append(list_of_points[t])
                (ave, min,
                 max) = utils.mean_confidence_interval(point_in_time,
                                                       confidence=0.95)
                CI_average.append(ave)
                CI_min.append(min)
                CI_max.append(max)
            ax.plot(list(CI_average),
                    color=list(
                        dict(mcolors.BASE_COLORS,
                             **mcolors.CSS4_COLORS).keys())[iteration],
                    label='k = %s subpops = %s' % (k, subnum))
            ax.plot(list(CI_min), "--", color="0.5")
            ax.plot(list(CI_max), "--", color="0.5")
            ax.fill_between(list(CI_average),
                            list(CI_max),
                            list(CI_min),
                            color="None",
                            linestyle="--")
    ax.legend(loc=2)
    ax.set_ylabel('Fst')
    ax.set_xlabel('Generation')
    plt.show()
    savefilename = output_path + "/summary-ci.png"
    summary_fig.savefig(savefilename, bbox_inches='tight')

    ## now the richness graph
    richness_sum_fig = plt.figure(figsize=(16, 9))
    ax = richness_sum_fig.add_subplot(111)

    iteration = -1
    for k in k_run_values:
        for subnum in subpop_run_values:
            iteration += 1
            CI_average = []
            CI_min = []
            CI_max = []
            for t in range(len(output[k][subnum][0].richness)):
                point_in_time = []
                for n in range(config.reps):
                    list_of_points = list(output[k][subnum][n].richness)
                    point_in_time.append(list_of_points[t])
                (ave, min,
                 max) = utils.mean_confidence_interval(point_in_time,
                                                       confidence=0.95)
                CI_average.append(ave)
                CI_min.append(min)
                CI_max.append(max)
            ax.plot(list(CI_average),
                    color=list(
                        dict(mcolors.BASE_COLORS,
                             **mcolors.CSS4_COLORS).keys())[iteration],
                    label='k = %s subpops = %s' % (k, subnum))
            ax.plot(list(CI_min), "--", color="0.5")
            ax.plot(list(CI_max), "--", color="0.5")
            ax.fill_between(list(CI_average),
                            list(CI_max),
                            list(CI_min),
                            color="None",
                            linestyle="--")
    ax.legend(loc=2)
    ax.set_ylabel('Richness')
    ax.set_xlabel('Generation')
    plt.show()
    savefilename = output_path + "/richness-ci.png"
    richness_sum_fig.savefig(savefilename, bbox_inches='tight')
Beispiel #15
0
generations = 10
heritability = 0.7
number_of_qtl = 50
number_of_replicates = 2
founders = [[2, 26], [3, 25], [4, 24], [5, 23]]
os_per_pair = 500
recombination_rates = [0.01] * 1478
prefounders = sim.loadPopulation(input_file_prefix + 'bia_prefounders.pop')
config_file_template = input_file_prefix + 'gwas_pipeline.xml'

sim.tagID(prefounders, reset=True)
alleles = np.array(
    pd.read_hdf(input_file_prefix + 'parameters/alleles_at_1478_loci.hdf'))

rdm_populations = sim.Simulator(prefounders,
                                number_of_replicates,
                                stealPops=False)
rdm_magic = breed.MAGIC(rdm_populations, founders, recombination_rates)
sim.tagID(prefounders, reset=27)
rdm_magic.generate_f_one(founders, os_per_pair)

sim.stat(rdm_populations.population(0), alleleFreq=sim.ALL_AVAIL)
af = analyze.allele_data(rdm_populations.population(0), alleles,
                         list(range(len(alleles))))
minor_alleles = np.asarray(af.minor_allele, dtype=np.int8)
rdm_magic.recombinatorial_convergence(rdm_populations, len(founders),
                                      os_per_pair)

study = analyze.Study(run_id)

sim.stat(rdm_populations.population(0),
Beispiel #16
0
def main():

    start = time()
    MAXALLELES = 10000

    parser = argparse.ArgumentParser()
    parser.add_argument("--experiment",
                        help="provide name for experiment",
                        required=True,
                        type=str)
    parser.add_argument(
        "--cores",
        type=int,
        help=
        "Number of cores to use for simuPOP, overrides devel flag and auto calculation"
    )
    parser.add_argument("--debug", help="turn on debugging output")
    parser.add_argument("--devel",
                        help="Use only half of the available CPU cores",
                        type=int,
                        default=1)
    parser.add_argument("--dbhost",
                        help="database hostname, defaults to localhost",
                        default="localhost")
    parser.add_argument("--dbport",
                        help="database port, defaults to 27017",
                        default="27017")
    parser.add_argument("--stepsize",
                        help="size of sample by proportion",
                        type=float,
                        default=1.0)
    parser.add_argument("--reps",
                        help="Replicated populations per parameter set",
                        type=int,
                        default=4)
    parser.add_argument(
        "--networkfile",
        help=
        "Name of GML file representing the  network model for this simulation",
        required=True,
        type=str)
    parser.add_argument("--numloci",
                        help="Number of loci per individual",
                        type=int,
                        required=True)
    parser.add_argument(
        "--maxinittraits",
        help="Max initial number of traits per locus for initialization",
        type=int,
        required=True)
    parser.add_argument(
        "--samplefraction",
        help=
        "Size of samples taken to calculate all statistics, as a proportion",
        type=float,
        required=True)
    parser.add_argument(
        "--innovrate",
        help=
        "Rate at which innovations occur in population as a per-locus rate",
        type=float,
        required=True)
    parser.add_argument(
        "--simlength",
        help=
        "Time at which simulation and sampling end, defaults to 3000 generations",
        type=int,
        default="3000")
    parser.add_argument(
        "--popsize",
        help="Initial size of population for each community in the model",
        type=int,
        required=True)
    parser.add_argument(
        "--migrationfraction",
        help="Fraction of population that migrates each time step",
        type=float,
        required=True,
        default=0.2)
    parser.add_argument(
        "--seed",
        type=int,
        help="Seed for random generators to ensure replicability")

    (config, sim_id, script, cores) = setup(parser)

    log.info("config: %s", config)

    beginCollectingData = cpm.expectedIAQuasiStationarityTimeHaploid(
        config.popsize, config.innovrate)
    log.info("Starting data collection at generation: %s", beginCollectingData)
    ### NOTE ###
    ###
    ### the simuPOP module is deliberately imported here because we need to process the
    ### command line arguments first, to understand which version of the simuPOP module (e.g.,
    ### long allele representation, etc, to import, and because we need to figure out how
    ### many cores the machine has, etc., to set it up for parallel processing.  If we import
    ### at the top of the file as normal, the imports happen before any code is executed,
    ### and we can't set those options.  DO NOT move these imports out of setup and main.
    import simuPOP as sim
    import demography as demo

    log.info("Starting simulation run %s", sim_id)
    log.debug("config: %s", config)
    if config.seed is None:
        log.info(
            "No random seed given, allowing RNGs to initialize with random seed"
        )
    else:
        log.debug("Seeding RNGs with seed: %s", config.seed)
        npr.seed(config.seed)
        random.seed(config.seed)

    full_command_line = " ".join(sys.argv)

    # Calculate the burn in time

    burn_time = rapanuisim.utils.simulation_burnin_time(
        config.popsize, config.innovrate)
    log.info("Minimum burn in time given popsize and theta: %s", burn_time)

    initial_distribution = rapanuisim.utils.constructUniformAllelicDistribution(
        config.maxinittraits)
    log.info("Initial allelic distribution (for each locus): %s",
             initial_distribution)

    #innovation_rate = pypopgen.wf_mutation_rate_from_theta(config.popsize, config.innovrate)
    innovation_rate = float(config.innovrate)
    log.info("Per-locus innov rate within populations: %s", innovation_rate)

    # Construct a demographic model from a collection of network slices which represent a temporal network
    # of changing subpopulations and interaction strengths.  This object is Callable, and simply is handed
    # to the mating function which applies it during the copying process
    networkmodel = demo.NetworkModel(
        networkmodel=config.networkfile,
        simulation_id=sim_id,
        sim_length=config.simlength,
        burn_in_time=burn_time,
        initial_subpop_size=config.popsize,
        migrationfraction=config.migrationfraction)

    # The regional network model defines both of these, in order to configure an initial population for evolution
    # Construct the initial population

    pop = sim.Population(size=networkmodel.get_initial_size(),
                         subPopNames=networkmodel.get_subpopulation_names(),
                         infoFields=networkmodel.get_info_fields(),
                         ploidy=1,
                         loci=config.numloci)

    log.info("population sizes: %s names: %s", pop.subPopSizes(),
             pop.subPopNames())
    initial_distribution = utils.constructUniformAllelicDistribution(
        config.numloci)
    log.info("Initial allelic distribution: %s", initial_distribution)

    # We are going to evolve the same population over several replicates, in order to measure how stochastic variation
    # effects the measured copying process.
    simu = sim.Simulator(pop, rep=config.reps)

    # Start the simulation and evolve the population, taking samples after the burn-in time has elapsed
    simu.evolve(
        initOps=sim.InitGenotype(freq=initial_distribution),
        preOps=[
            sim.PyOperator(func=sampling.logGenerationCount,
                           param=(),
                           step=100,
                           reps=0)
        ],
        matingScheme=sim.RandomSelection(subPopSize=networkmodel),
        postOps=[
            sim.KAlleleMutator(k=MAXALLELES,
                               rates=config.innovrate,
                               loci=sim.ALL_AVAIL),
            #                  sim.PyOperator(func=rapanuisim.data.sampleNumAlleles,
            #                                 param=(config.samplefraction, config.innovrate, config.popsize, sim_id, config.numloci),
            #                                 step=1, begin=beginCollectingData),
            #                  sim.PyOperator(func=rapanuisim.data.sampleTraitCounts,
            #                                 param=(config.samplefraction, config.innovrate, config.popsize, sim_id, config.numloci),
            #                                 step=1, begin=beginCollectingData),
            #                  sim.PyOperator(func=rapanuisim.data.censusTraitCounts,
            #                                 param=(config.innovrate, config.popsize, sim_id, config.numloci), step=1,
            #                                 begin=beginCollectingData),
            #                  sim.PyOperator(func=rapanuisim.data.censusNumAlleles,
            #                                 param=(config.innovrate, config.popsize, sim_id, config.numloci), step=1,
            #                                 begin=beginCollectingData)
            #                  #sim.PyOperator(func=rapanuisim.data.sampleIndividuals,
            #                  ##               param=(config.samplefraction, config.innovrate, config.popsize, sim_id, config.numloci),
            #                  #               step=1, begin=beginCollectingData),
        ],
        gen=3000)

    endtime = time()
    elapsed = endtime - start
    #log.info("simulation complete in %s seconds with %s cores", elapsed, cores)
    log.info("simulation complete,%s,%s", cores, elapsed)
    log.info("Ending simulation run at generation %s",
             simu.population(0).dvars().gen)
    sampled_length = int(config.simlength) - burn_time
Beispiel #17
0
proportion_of_individuals_saved = 0.05
overshoot_as_proportion = 0.50
individuals_per_breeding_subpop = 5
heritability = 0.7
metapop_sample_size = 100

nam = sim.loadPopulation('nam_prefounders.pop')
sim.tagID(prefounders, reset=True)
founders = [1, 5, 7, 8]
pop = prefounders.clone()
ep.arbitrary_ordering_of_founders(prefounders, pop, founders)
ep.generate_f_one(pop)
ep.generate_f_two(pop)
ep.mate_and_merge(pop)
ep.interim_random_mating(pop, generations_of_random_mating)
ep.replicates = sim.Simulator(pop, stealPops=False, rep=number_of_replicates)
ep.meta_replicates = sim.Simulator(pop, rep=number_of_replicates)
"""
# Remove individuals which are initially present in Simulator objects
"""
for meta_rep in ep.meta_replicates.populations():
    meta_rep.removeIndividuals(list(range(meta_rep.popSize())))

ep.pure_selection(ep.replicates, ep.meta_replicates)

syn = helpers.Synbreed()
"""
# Allele frequencies and output
"""
# Note: In PCA I should get the same results from the minor allele frequency
# as the major allele frequency
Beispiel #18
0
    'aggregate': {},
    'selected': {},
    'non-selected': {}
}

s = selection.Truncation(
    sim_params['gens_selection'], sim_params['gens_random_mating'],
    sim_params['main_pop_size'], sim_params['proportion_saved'],
    sim_params['overshoot'], sim_params['breeding_inds_per_sp'],
    sim_params['heritability'], sim_params['sample_sizes'],
    sim_params['replicates'])

sim.tagID(nam, reset=True)

founders = sim_params['founders']
replicated_nam = sim.Simulator(nam, rep=2)
pop = replicated_nam.extract(0)
pop.dvars().statistics = population_statistics
meta = replicated_nam.extract(0)
#meta.removeSubPops(0)

# ### Simulated Breeding Scenario ###

# In[ ]:

s.generate_f_one(pop, recombination_rates, sim_params['founders'])
s.expand_by_selfing(pop, recombination_rates)
s.mate_and_merge(pop, recombination_rates)
s.interim_random_mating(pop, recombination_rates)

sim.stat(pop,
Beispiel #19
0
# (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=1), rep=5)
simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.5, 0.5])
    ],
    matingScheme = sim.RandomMating(),
    postOps=[
        sim.Stat(alleleFreq=0),
        sim.TerminateIf('len(alleleFreq[0]) == 1')
    ]
)

Beispiel #20
0
# In[ ]:

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

# In[ ]:

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

# ### Run MAGIC Mating Scheme

# In[ ]:

s.generate_f_one(pop, recombination_rates, sim_params['founders'])
s.recombinatorial_convergence(pop, recombination_rates)
s.expand_by_selfing(pop, recombination_rates)
s.interim_random_mating(pop, recombination_rates)

# ## Adapting QTL and Allele Effects to Multiple Replicate Case

# In[ ]:
Beispiel #21
0
import simuOpt
simuOpt.setOptions(quiet=True, alleleType='long')
import simuPOP as sim
pop = sim.Population(size=1000, loci=[1])
simu = sim.Simulator(pop, 5)
simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.PyExec('introGen=[]')
    ],
    preOps=[
        sim.Stat(alleleFreq=0),
        sim.IfElse('alleleFreq[0][1] == 0', ifOps=[
            sim.PointMutator(loci=0, allele=1, inds=0),
            sim.PyExec('introGen.append(gen)')
        ]),
        sim.TerminateIf('alleleFreq[0][1] >= 0.05')
    ],
    matingScheme=sim.RandomMating()
)
# number of attempts
print([len(x.dvars().introGen) for x in simu.populations()])
# age of mutant
print([x.dvars().gen - x.dvars().introGen[-1] for x in simu.populations()])
Beispiel #22
0
        #print(geno[0], geno[1], v)
        return v

def sizeChange(gen):
    if gen <= 40:
        v = Fixed_pop_size
        #print(geno[0],v)
        return v
    else:
        v = Fixed_pop_size2
        #print(geno[0], geno[1], v)
        return v



simu = sim.Simulator(pop1,rep=Replicates)


simu.evolve(
    initOps=[
    ],
    preOps=[

                        ],
    matingScheme=sim.RandomMating(subPopSize=sizeChange,numOffspring=(sim.POISSON_DISTRIBUTION, Offspring_Poisson_dist_mean),ops=sim.Recombinator(loci=[0, 1, 2, 3, 4, 5, 6, 7], rates=[0.095162582,	0.075960076,	0.094257292,	0.154646165,	0.005,	0.104165865,	0.071328306,0.5]))

    ,
    postOps=[
            sim.PySelector(loci=[4], func=sel),
            sim.Stat(alleleFreq=[0,1,2,3,4,5,6,7],numOfMales=True,popSize=True),
Beispiel #23
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
simu = sim.Simulator(sim.Population(50, loci=[10], ploidy=1),
    rep=3)
simu.evolve(gen = 5)
simu.dvars(0).gen
simu.evolve(
    initOps=[sim.InitGenotype(freq=[0.5, 0.5])],
    matingScheme=sim.RandomSelection(),
    postOps=[
        sim.Stat(alleleFreq=5),
        sim.IfElse('alleleNum[5][0] == 0',
            sim.PyEval(r"'Allele 0 is lost in rep %d at gen %d\n' % (rep, gen)")),
        sim.IfElse('alleleNum[5][0] == 50',
            sim.PyEval(r"'Allele 0 is fixed in rep %d at gen %d\n' % (rep, gen)")),
        sim.TerminateIf('len(alleleNum[5]) == 1'),
    ],
)
[simu.dvars(x).gen for x in range(3)]
Beispiel #24
0
# for details.
#
# Copyright (C) 2004 - 2010 Bo Peng ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

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

import simuPOP as sim
simu = sim.Simulator(sim.Population(100), rep=10)
simu.evolve(
    initOps=[sim.InitSex(), sim.InitGenotype(freq=[0.5, 0.5])],
    matingScheme=sim.RandomMating(),
    postOps=[sim.Pause(stopOnKeyStroke=str(x), reps=x) for x in range(10)],
    gen=100)
Beispiel #25
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,
)
Beispiel #26
0
    post_ops['Stat-richness'] = sp.Stat(
        alleleFreq=[0],
        haploFreq=[0],
        vars=['alleleFreq', 'haploFreq', 'alleleNum', 'genoNum'])
    post_ops['fst_acumulation'] = sp.PyOperator(update_acumulator,
                                                param=['fst', 'F_st'])
    post_ops['richness_acumulation'] = sp.PyOperator(
        update_richness_acumulator, param=('alleleFreq', 'Freq of Alleles'))
    post_ops['class_richness'] = sp.PyOperator(
        sampleAlleleAndGenotypeFrequencies, param=(pop_size, num_loci))

    mating_scheme = sp.RandomSelection()
    #mating_scheme=sp.RandomSelection(subPopSize=sub_pop_size)

    ## go simuPop go! evolve your way to the future!
    sim = sp.Simulator(pops)  #, rep=3)

    sim.evolve(initOps=list(init_ops.values()),
               preOps=list(pre_ops.values()),
               postOps=list(post_ops.values()),
               matingScheme=mating_scheme,
               gen=num_gens)

    print("now evolving... k= %s" % param_value)

    # now make a figure of the Fst results
    fig = plt.figure(figsize=(16, 9))
    ax = fig.add_subplot(111)
    for pop, mig in zip(sim.populations(), migs):
        ax.plot(pop.dvars().fst, label='Migration rate %.4f' % mig)
    ax.legend(loc=2)
Beispiel #27
0
pop = sim.Population(100, loci=5, chromNames=['chrom1'])
pop.dvars().name = 'my sim.Population'
pop.save('sample.pop')
pop1 = sim.loadPopulation('sample.pop')

# genetic drift with replication
startfreq = .2
gens = 101
steps = 1
reps = 10
popsize = 100
loci = 5
f = open('simtest_stats.txt', 'w+')
f.write('freq,rep\n' + str(startfreq) + ',' + str(reps))
f.close()
simu = sim.Simulator(sim.Population(size=popsize, loci=loci), rep=reps)
f = open('simtest_out_rep.txt', 'w+')
f.write('gen,freq,rep\n')
f.close()
simu.evolve(
    initOps=[
        sim.InitGenotype(
            freq=[startfreq, 1 -
                  startfreq]),  # initalize genotypes with, 2 alleles w/ freq
        sim.InitSex(),
        # sim.Stat(alleleFreq=0),
        # sim.PyEval(r"'%d,%.2f,%d\n' % (gen, alleleFreq[0][0], rep)",
        #            begin=0,reps=sim.ALL_AVAIL,
        #            output='>>>simtest_out_rep.txt')
    ],
    # preOps=[                                             # do stuff before evolve
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--experiment", help="provide name for experiment", required=True, type=str, default="test")
    parser.add_argument("--debug", help="turn on debugging output")
    parser.add_argument("--reps", help="Replicated populations per parameter set", type=int, default=3)
    parser.add_argument("--networkfile", help="Name of GML file representing the  network model for this simulation",
                        required=True, type=str, default="smallworld")
    parser.add_argument("--numloci", help="Number of loci per individual (use with care)", type=int, required=True, default=1)
    parser.add_argument("--maxinittraits", help="Max initial number of traits per locus for initialization", type=int,
                        required=True, default=50)
    parser.add_argument("--innovrate", nargs='+', help="Rate(s) at which innovations occur in population as a per-locus rate", type=float, default=[])
    parser.add_argument("--simlength", help="Time at which simulation and sampling end, defaults to 3000 generations",
                        type=int, default="20")
    parser.add_argument("--popsize", help="Initial size of population for each community in the model", type=int, required=True)
    parser.add_argument("--migrationfraction", nargs='+', help="Fraction of population that migrates each time step", type=float, required=True, default=[])
    parser.add_argument("--seed", type=int, help="Seed for random generators to ensure replicability")
    parser.add_argument( "--k_values", nargs='+', type=int, help="list of k-values to explore [e.g., 2 4 20 24]", default=[])
    parser.add_argument("--sub_pops", nargs="+", help="Number of sub populations", required=True, default=[])
    parser.add_argument("--maxalleles", type=int, help="Maximum number of alleles", default=50)
    parser.add_argument("--save_figs", type=bool, help="Save figures or not?", default=False)
    parser.add_argument("--burnintime", type=int, help="How long to wait before making measurements? ", default=2000)
    parser.add_argument("--rewiringprob", type=float, help="Probability of random rewiring", default=0)

    config = parser.parse_args()

    # setup output directories for writing
    output_path = utils.setup_output(config.experiment)

    # check the k and migration rate combinations
    check = utils.check_k_and_migration_rates(config)
    if check is not True:
        print("\nProblem(s):\t %s\n" % check)
        print("Please adjust input values for k and/or migration rate and restart.\n ")
        sys.exit()
    else:
        print("\nChecked on the migration and k values -- all looks good!\n")

    # save parameters
    utils.save_parameters(str(sys.argv), config, output_path)

    # set up the frequencies for the alleles in each loci. Here assuming a uniform distribution as a starting point
    distribution = utils.constructUniformAllelicDistribution(config.maxinittraits)

    # prepare file for output
    output_data_file_name = "%s/%s-rare-trait-output.csv" % (output_path, config.experiment)
    with open(output_data_file_name, mode='w') as output_file:
        output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        output_writer.writerow(["Iteration", "k", "NumSubPops", "Migration", "InnovationRate", "Ones_Mean",
                                "Ones_95%_Lower", "Ones_95%_Upper", "Twos_Mean", "Twos_95%_Lower", "Twos_95%_Upper", "Richness_Mean",
                                "Richness_95%_Lower", "Richness_95%_Upper","Fst_Mean","Fst_95%_Lower","Fst_95%_Upper"])
        output_file.flush()
        subpop_run_values = config.sub_pops
        k_run_values = config.k_values
        mig_run_values = config.migrationfraction
        innov_run_values = config.innovrate

        iteration=-1

        for subpop in subpop_run_values:
            if k_run_values == [0]:
                k_run_values = [2, int(float(subpop) * .1), int(float(subpop) * .2),
                            int(float(subpop) * .5), int(float(subpop) * .8),
                            int(float(subpop) * .9),
                            int(subpop) - 1]

            for k in k_run_values:
                for mig in mig_run_values:
                    for innov in innov_run_values:
                        ## let us know whats happening
                        iteration += 1
                        print("Now running with subpops: %s k-value: %s mig rate: %4f innov rate: %4f" % (subpop,k,mig,innov))
                        ## these are lists of things that simuPop will do at different stages
                        init_ops = OrderedDict()
                        pre_ops = OrderedDict()
                        post_ops = OrderedDict()

                        # Construct a demographic model
                        #networkmodel = NetworkModel( networkmodel="/Users/clipo/Documents/PycharmProjects/RapaNuiSim/notebooks/test_graph.gml",
                        networkmodel = network.NetworkModel( networkmodel=config.networkfile,
                                                         simulation_id=config.experiment,
                                                         sim_length=config.simlength,
                                                         burn_in_time=config.burnintime,
                                                         initial_subpop_size=config.popsize,
                                                         migrationfraction=mig,
                                                         sub_pops=subpop,
                                                         connectedness=k, # if 0, then distance decay
                                                         save_figs=config.save_figs,
                                                         network_iteration=iteration)

                        num_pops = networkmodel.get_subpopulation_number()
                        sub_pop_size = int(config.popsize / num_pops)

                        # The regional network model defines both of these, in order to configure an initial population for evolution
                        # Construct the initial population
                        pops = sp.Population(size = [sub_pop_size]*num_pops,
                                         subPopNames = str(list(networkmodel.get_subpopulation_names())),
                                         infoFields = 'migrate_to',
                                         ploidy=1,
                                         loci=config.numloci )

                        ### now set up the activities
                        init_ops['acumulators'] = sp.PyOperator(utils.init_acumulators, param=['fst','alleleFreq', 'haploFreq'])
                        init_ops['subpop_counts'] = sp.PyOperator(utils.init_count_traits_in_subpops)
                        init_ops['Sex'] = sp.InitSex()
                        init_ops['Freq'] = sp.InitGenotype(loci=list(range(config.numloci)),freq=distribution)

                        post_ops['Innovate'] = sp.KAlleleMutator(k=config.maxalleles, rates=innov, loci=sp.ALL_AVAIL)
                        post_ops['mig']=sp.Migrator(rate=networkmodel.get_migration_matrix()) #, reps=[3])
                        post_ops['Stat-fst'] = sp.Stat(structure=sp.ALL_AVAIL)
                        post_ops['Stat-richness']=sp.Stat(alleleFreq=[0], haploFreq=[0], vars=['alleleFreq','haploFreq','alleleNum', 'genoNum'])
                        post_ops['fst_acumulation'] = sp.PyOperator(utils.update_acumulator, param=['fst','F_st'])
                        post_ops['richness_acumulation'] = sp.PyOperator(utils.update_richness_acumulator, param=('alleleFreq', 'Freq of Alleles'))
                        post_ops['class_richness']=sp.PyOperator(utils.calculateAlleleAndGenotypeFrequencies, param=(config.popsize,config.numloci))
                        post_ops['count_traits_in_subpops'] = sp.PyOperator(utils.count_traits_in_subpops, param=(config.numloci,num_pops), subPops=sp.ALL_AVAIL)

                        mating_scheme = sp.RandomSelection()

                        ## go simuPop go! evolve your way to the future!
                        sim = sp.Simulator(pops, rep=config.reps)
                        sim.evolve(initOps=list(init_ops.values()), preOps=list(pre_ops.values()), postOps=list(post_ops.values()),
                               matingScheme=mating_scheme, gen=config.simlength)

                        count=0
                        for pop in sim.populations():
                            output[count] = deepcopy(pop.dvars())
                            count+=1

                        ones_point_in_time = []
                        twos_point_in_time = []
                        richness_point_in_time = []
                        fst_point_in_time = []

                        for n in range(config.reps):
                            list_of_ones = list(output[n].ones)
                            list_of_twos = list(output[n].twos)
                            list_of_richness = list(output[n].richness)
                            list_of_fst = list(output[n].fst)
                            ones_point_in_time.append(list_of_ones[2000])
                            twos_point_in_time.append(list_of_twos[2000])
                            richness_point_in_time.append(list_of_richness[2000])
                            fst_point_in_time.append(list_of_fst[2000])

                        (ones_ave, ones_min, ones_max) = utils.mean_confidence_interval(ones_point_in_time,
                                                                                    confidence=0.95)
                        (twos_ave, twos_min, twos_max) = utils.mean_confidence_interval(twos_point_in_time,
                                                                                    confidence=0.95)
                        (richness_ave, richness_min, richness_max) = utils.mean_confidence_interval(richness_point_in_time,
                                                                                                confidence=0.95)
                        (fst_ave, fst_min, fst_max) = utils.mean_confidence_interval(fst_point_in_time,
                                                                                 confidence=0.95)

                        output_writer.writerow([iteration,k,subpop,mig,innov,ones_ave,ones_min,ones_max,
                                            twos_ave,twos_min,twos_max,richness_ave,richness_min,richness_max,fst_ave,fst_min,fst_max])
                        output_file.flush()
Beispiel #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)
def createSim(pop, reps):
    sim = sp.Simulator(pop, rep=reps)
    return sim