コード例 #1
0
ファイル: reichEvolve.py プロジェクト: sudorook/simuPOP
def simulate(model, N0, N1, G0, G1, spec, s, mu, k):
    '''Evolve a sim.Population using given demographic model
    and observe the evolution of its allelic spectrum.
    model: type of demographic model.
    N0, N1, G0, G1: parameters of demographic model.
    spec: initial allelic spectrum, should be a list of allele
        frequencies for each allele.
    s: selection pressure.
    mu: mutation rate.
    k: k for the k-allele model
    '''
    demo_func = demo_model(model, N0, N1, G0, G1)
    pop = sim.Population(size=demo_func(0), loci=1, infoFields='fitness')
    pop.evolve(
        initOps=[
            sim.InitSex(),
            sim.InitGenotype(freq=spec, loci=0)
        ],
        matingScheme=sim.RandomMating(subPopSize=demo_func),
        postOps=[
            sim.KAlleleMutator(k=k, rates=mu),
            sim.MaSelector(loci=0, fitness=[1, 1, 1 - s], wildtype=0),
            ne(loci=[0], step=100),
            sim.PyEval(r'"%d: %.2f\t%.2f\n" % (gen, 1 - alleleFreq[0][0], ne[0])',
                step=100),
        ],
        gen = G0 + G1
    )
コード例 #2
0
    global counter
    for line in mutants.split('\n'):
        # a trailing \n will lead to an empty string
        if not line:
            continue
        (gen, loc, ploidy, a1, a2, id) = line.split('\t')
        counter[int(loc)] += 1


pop = sim.Population(
    [5000] * 3,
    loci=[2, 1, 1],
    infoFields='ind_id',
    chromTypes=[sim.AUTOSOME, sim.CHROMOSOME_X, sim.CHROMOSOME_Y])
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.5, 0.5]),
        sim.IdTagger(),
    ],
    preOps=[
        sim.KAlleleMutator(rates=[0.001] + [0.01] * 3,
                           loci=range(4),
                           k=100,
                           output=countMutants),
    ],
    matingScheme=sim.RandomMating(
        ops=[sim.IdTagger(), sim.MendelianGenoTransmitter()]),
    gen=10)
print(counter.items())
コード例 #3
0
import simuOpt
simuOpt.setOptions(quiet=True, alleleType='long')
import simuPOP as sim
pop = sim.Population(size=[2500]*10, loci=1)
simu = sim.Simulator(pop, rep=2)
simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(genotype=20),
    ],
    preOps=[
        sim.StepwiseMutator(rates=0.0001, reps=0),
        sim.KAlleleMutator(k=10000, rates=0.0001, reps=1),
    ],
    matingScheme=sim.RandomMating(),
    postOps=[
        # Use vars=['alleleFreq_sp'] to calculate allele frequency for
        # each subpopulation
        sim.Stat(alleleFreq=0, vars=['alleleFreq_sp'], step=200),
        sim.PyEval('gen', step=200, reps=0),
        sim.PyEval(r"'\t%.2f' % (sum([len(subPop[x]['alleleFreq'][0]) "
            "for x in range(10)])/10.)", step=200),
        sim.PyOutput('\n', reps=-1, step=200)
    ],
    gen=601
)
コード例 #4
0
ファイル: alleleMapping.py プロジェクト: sudorook/simuPOP
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

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

import simuPOP as sim
pop = sim.Population(size=[2000], loci=1)
pop.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0] * 4 + [0.1, 0.2, 0.3, 0.4])
    ],
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.KAlleleMutator(k=4,
                           rates=1e-4,
                           mapIn=[0] * 4 + list(range(4)),
                           mapOut=[4, 5, 6, 7]),
        sim.Stat(alleleFreq=0, step=100),
        sim.PyEval(
            r"', '.join(['%.2f' % alleleFreq[0][x] for x in range(8)]) + '\n'",
            step=100),
    ],
    gen=500)
コード例 #5
0
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,
                       param=(args.samplesize, args.mutationrate, args.popsize,
                              sim_id, args.numloci),
                       step=args.stepsize,
                       begin=beginCollectingData),
        sim.PyOperator(func=data.sampleTraitCounts,
                       param=(args.samplesize, args.mutationrate, args.popsize,
                              sim_id, args.numloci),
                       step=args.stepsize,
                       begin=beginCollectingData),
        sim.PyOperator(func=data.censusTraitCounts,
                       param=(args.mutationrate, args.popsize, sim_id,
                              args.numloci),
                       step=args.stepsize,
コード例 #6
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=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()
コード例 #7
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
コード例 #8
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')
コード例 #9
0
    # 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=networkmodel.get_initial_size(),
                         subPopNames=str(
                             list(networkmodel.get_subpopulation_names())),
                         infoFields='migrate_to',
                         ploidy=1,
                         loci=100)

    ### now set up the activities
    init_ops['acumulators'] = sp.PyOperator(
        init_acumulators, param=['fst', 'alleleFreq', 'haploFreq'])
    init_ops['Sex'] = sp.InitSex()
    init_ops['Freq'] = sp.InitGenotype(loci=0, freq=distribution)
    post_ops['Innovate'] = sp.KAlleleMutator(k=MAXALLELES,
                                             rates=innovation_rate,
                                             loci=sp.ALL_AVAIL)
    #post_ops['mig'] = sp.Migrator(demography.migrIslandRates(migration_rate, num_pops)) #, reps=[i])
    post_ops['mig'] = sp.Migrator(rate=networkmodel.get_migration_matrix())
    #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['haploFreq']=sp.stat(pops, haploFreq=[0], vars=['haploFreq', 'haploNum'])
    #post_ops['alleleFreq']=sp.stat(pops, alleleFreq=sp.ALL_AVAIL)

    post_ops['Stat-richness'] = sp.Stat(
        alleleFreq=[0],
        haploFreq=[0],
        vars=['alleleFreq', 'haploFreq', 'alleleNum', 'genoNum'])
    post_ops['fst_acumulation'] = sp.PyOperator(update_acumulator,
コード例 #10
0
ファイル: KAlleleMutator.py プロジェクト: sudorook/simuPOP
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

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

import simuPOP as sim
pop = sim.Population(size=[2000], loci=1 * 3)
pop.evolve(
    initOps=sim.InitSex(),
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.KAlleleMutator(k=5, rates=[1e-2, 1e-3], loci=[0, 1]),
        sim.Stat(alleleFreq=range(3), step=100),
        sim.PyEval(
            r"', '.join(['%.3f' % alleleFreq[x][0] for x in range(3)]) + '\n'",
            step=100),
    ],
    gen=500)
コード例 #11
0
def evolvePop(model,
              N0,
              N1,
              G0,
              G1,
              initSpec,
              mu,
              k,
              fitness,
              m=1,
              migrRate=0,
              logfile='',
              sp_logfile='',
              **kwargs):
    '''Evolve a population with specified allele frequencies (parameter
    initSpec) using given demographic (model, N0, N1, G0, G1, m), mutation
    (a k-allele model with parameters mu and k) and natural selection models
    (a multi-locus selection model with fitness vector s). Total disease
    allele frequency and effective number of alleles in the population
    and in all subpopulations are recorded if names of log files are provided.
    This function returns a tuple of these two statistics at the end of the
    evolution. Additional keyword arguments could be used to control when and
    how often statisitcs are outputed.
    '''
    L = len(fitness) // 3
    if not hasattr(mu, '__iter__'):  # if a single mutation rate is given
        mu = [mu] * L
    # Create expressions to output f_e and ne at all loci, which are
    #   "%d\t%.4f\t%.4f\n" % (gen, 1-alleleFreq[x][0], ne[x])
    # for locus x.
    statExpr = '"%d' + r'\t%.4f\t%.4f'*L + r'\n" % (gen,' + \
        ', '.join(['1-alleleFreq[%d][0], ne[%d]' % (x, x) for x in range(L)]) + ')'
    demo_func = demoModel(model, N0, N1, G0, G1, m)
    pop = sim.Population(size=demo_func(0),
                         loci=[1] * L,
                         infoFields=['fitness', 'migrate_to'])
    pop.evolve(
        initOps=[sim.InitSex(), sim.InitGenotype(freq=initSpec)],
        preOps=[
            sim.KAlleleMutator(k=k, rates=mu, loci=range(L)),
            sim.MlSelector([
                sim.MaSelector(loci=i, fitness=fitness[3 * i:3 * (i + 1)])
                for i in range(L)
            ],
                           mode=sim.MULTIPLICATIVE),
            sim.Migrator(rate=migrIslandRates(migrRate, m), begin=G0 + 1),
        ],
        matingScheme=sim.RandomMating(subPopSize=demo_func),
        postOps=[
            sim.IfElse(
                logfile != '' or sp_logfile != '',
                Ne(loci=sim.ALL_AVAIL,
                   vars=['ne'] if m == 1 else ['ne', 'ne_sp']), **kwargs),
            sim.IfElse(logfile != '',
                       sim.PyEval(statExpr, output='>>' + logfile), **kwargs),
            sim.IfElse(
                m > 1 and sp_logfile != '',
                sim.PyEval(
                    statExpr,
                    output='>>' + sp_logfile,
                    # subPops=sim.ALL_AVAIL will evalulate the expression in each
                    # subpopulation's local namespace (vars(sp)).
                    subPops=sim.ALL_AVAIL,
                    begin=G0),
                **kwargs),
        ],
        finalOps=Ne(loci=sim.ALL_AVAIL),
        gen=G0 + G1)
    return tuple([1-pop.dvars().alleleFreq[x][0] for x in range(L)] + \
        [pop.dvars().ne[x] for x in range(L)])
コード例 #12
0
             sim_length)

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

    simu.evolve(
        initOps=sim.InitGenotype(freq=initial_distribution),
        preOps=[
            sim.PyOperator(func=utils.logGenerationCount,
                           param=(),
                           step=gen_logging_interval,
                           reps=0),
        ],
        matingScheme=sim.RandomSelection(),
        postOps=[
            sim.KAlleleMutator(k=simconfig.MAXALLELES, rates=mut),
            sim.PyOperator(func=data.sampleNumAlleles,
                           param=(sample_size, mut, popsize, sim_id, numloci),
                           step=sampling_interval,
                           begin=time_start_stats),
            sim.PyOperator(func=data.sampleTraitCounts,
                           param=(sample_size, mut, popsize, sim_id, numloci),
                           step=sampling_interval,
                           begin=time_start_stats),
            sim.PyOperator(func=data.censusTraitCounts,
                           param=(mut, popsize, sim_id, numloci),
                           step=sampling_interval,
                           begin=time_start_stats),
            sim.PyOperator(func=data.censusNumAlleles,
                           param=(mut, popsize, sim_id, numloci),
                           step=sampling_interval,
コード例 #13
0
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed
# description of this example.
#

import simuPOP as sim
pop = sim.Population(5000, loci=[1, 1])
pop.evolve(
    initOps=[sim.InitSex(), sim.InitGenotype(genotype=[50, 50])],
    preOps=[
        # the first locus uses a pure stepwise mutation model
        sim.StepwiseMutator(rates=0.001, loci=0),
        # the second locus uses a mixed model
        sim.MixedMutator(rates=0.001,
                         loci=1,
                         mutators=[
                             sim.KAlleleMutator(rates=1, k=100),
                             sim.StepwiseMutator(rates=1)
                         ],
                         prob=[0.1, 0.9])
    ],
    matingScheme=sim.RandomMating(),
    gen=20)
# what alleles are there?
geno0 = []
geno1 = []
for ind in pop.individuals():
    geno0.extend([ind.allele(0, 0), ind.allele(0, 1)])
    geno1.extend([ind.allele(1, 0), ind.allele(1, 1)])

print('Locus 0 has alleles', ', '.join([str(x) for x in set(geno0)]))
print('Locus 1 has alleles', ', '.join([str(x) for x in set(geno1)]))