Beispiel #1
0
    def setUp(self):
        import fwdpy11
        import numpy as np
        self.N = 1000
        self.demography = np.array([self.N] * self.N, dtype=np.uint32)
        self.rho = 1.
        self.theta = 100.
        self.nreps = 500
        self.mu = self.theta / (4 * self.N)
        self.r = self.rho / (4 * self.N)

        self.GSS = fwdpy11.GSS(VS=1, opt=0)
        a = fwdpy11.Additive(2.0, self.GSS)
        self.p = {
            'nregions': [],
            'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
            'recregions': [fwdpy11.Region(0, 1, 1)],
            'rates': (0.0, 0.025, self.r),
            'gvalue': a,
            'prune_selected': False,
            'demography': self.demography
        }
        self.params = fwdpy11.ModelParams(**self.p)
        self.rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
        self.pop = fwdpy11.DiploidPopulation(self.N, 1.0)
        fwdpy11.evolvets(self.rng, self.pop, self.params, 100)
def runsim(args):
    rng = fwdpy11.GSLrng(args.seed)

    pdict = {'gvalue': fwdpy11.Multiplicative(FITNESS_SCALING),
             'rates': (0., args.mu, None),
             'nregions': [],
             'sregions': [fwdpy11.GammaS(0., GENOME_LENGTH, 1.0-args.proportion,
                                         args.mean, args.shape, FITNESS_SCALING/2.0,
                                         scaling=2*args.popsize, label=1),
                          fwdpy11.ConstantS(0, GENOME_LENGTH, args.proportion, TWONS,
                                            FITNESS_SCALING/2.0, label=2,
                                            scaling=2*args.popsize)],
             'recregions': [fwdpy11.PoissonInterval(0, GENOME_LENGTH, args.recrate)],
             'demography': np.array([args.popsize]*SIMLEN*args.popsize, dtype=np.uint32),
             # This could easily be True for these sims:
             'prune_selected': False
             }
    params = fwdpy11.ModelParams(**pdict)

    pop = fwdpy11.DiploidPopulation(args.popsize, GENOME_LENGTH)

    sampler = fwdpy11.RandomAncientSamples(
        args.seed, args.popsize, [i for i in range(10*pop.N, SIMLEN*pop.N)])

    # With a lot of ancient samples:
    # 1. RAM use already skyrockets
    # 2. Simplification slows down
    # So, we should do it a little less often:
    fwdpy11.evolvets(rng, pop, params, 1000, sampler,
                     suppress_table_indexing=True)

    return pop
Beispiel #3
0
def runsim(args):
    popsizes = np.array([args.popsize] * 20 * args.popsize, dtype=np.int32)
    pop = fwdpy11.DiploidPopulation(args.popsize, 1.0)
    sregions = [fwdpy11.GaussianS(0, 1, 1, args.sigma)]
    recregions = [fwdpy11.PoissonInterval(0, 1, args.recrate)]

    optima = fwdpy11.GSSmo([(0, 0, args.VS),
                            (10 * args.popsize, args.opt, args.VS)])
    p = {
        'nregions': [],  # No neutral mutations -- add them later!
        'gvalue': fwdpy11.Additive(2.0, optima),
        'sregions': sregions,
        'recregions': recregions,
        'rates': (0.0, args.mu, None),
        # Keep mutations at frequency 1 in the pop if they affect fitness.
        'prune_selected': False,
        'demography': np.array(popsizes, dtype=np.uint32)
    }
    params = fwdpy11.ModelParams(**p)
    rng = fwdpy11.GSLrng(args.seed)
    s = Recorder(args.popsize)
    fwdpy11.evolvets(rng,
                     pop,
                     params,
                     100,
                     s,
                     suppress_table_indexing=True,
                     track_mutation_counts=True)
    return pop
def runsim(args):
    popsizes = np.array([args.popsize] * 20 * args.popsize, dtype=np.int32)
    locus_boundaries = [(i, i + 11) for i in range(0, 10 * 11, 11)]
    sregions = [fwdpy11.GaussianS(i[0] + 5, i[0] + 6, 1, args.sigma)
                for i in locus_boundaries]
    recregions = [fwdpy11.PoissonInterval(
        *i, args.rho / (4 * args.popsize)) for i in locus_boundaries]
    recregions.extend([fwdpy11.BinomialPoint(i[1], 0.5)
                       for i in locus_boundaries[:-1]])
    pop = fwdpy11.DiploidPopulation(args.popsize, locus_boundaries[-1][1])

    optima = fwdpy11.GSSmo(
        [(0, 0, args.VS), (10 * args.popsize, args.opt, args.VS)])
    p = {'nregions': [],  # No neutral mutations -- add them later!
         'gvalue': fwdpy11.Additive(2.0, optima),
         'sregions': sregions,
         'recregions': recregions,
         'rates': (0.0, args.mu, None),
         # Keep mutations at frequency 1 in the pop if they affect fitness.
         'prune_selected': False,
         'demography':  np.array(popsizes, dtype=np.uint32)
         }
    params = fwdpy11.ModelParams(**p)
    rng = fwdpy11.GSLrng(args.seed)
    s = Recorder(args.popsize)
    fwdpy11.evolvets(rng, pop, params, 100, s,
                     suppress_table_indexing=True,
                     track_mutation_counts=True)
    return pop
Beispiel #5
0
 def setUp(self):
     self.N = 1000
     self.demography = np.array([self.N] * 100, dtype=np.uint32)
     self.rho = 1.
     self.theta = 100.
     self.nreps = 500
     self.mu = self.theta / (4 * self.N)
     self.r = self.rho / (4 * self.N)
     self.GSS = fwdpy11.GSS(VS=1, opt=0)
     a = fwdpy11.Additive(2.0, self.GSS)
     self.p = {
         'nregions': [],
         'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
         'recregions': [fwdpy11.Region(0, 1, 1)],
         'rates': (0.0, 0.025, self.r),
         'gvalue': a,
         'prune_selected': False,
         'demography': self.demography
     }
     self.params = fwdpy11.ModelParams(**self.p)
     self.rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
     self.pop = fwdpy11.DiploidPopulation(self.N, 1.0)
     self.recorder = fwdpy11.RandomAncientSamples(
         seed=42, samplesize=10, timepoints=[i for i in range(1, 101)])
     fwdpy11.evolvets(self.rng, self.pop, self.params, 100, self.recorder)
Beispiel #6
0
def set_up_quant_trait_model():
    # TODO add neutral variants
    N = 1000
    demography = np.array([N] * 10 * N, dtype=np.uint32)
    rho = 1.
    # theta = 100.
    # nreps = 500
    # mu = theta/(4*N)
    r = rho / (4 * N)

    GSSmo = fwdpy11.GSSmo([(0, 0, 1), (N, 1, 1)])
    a = fwdpy11.Additive(2.0, GSSmo)
    p = {
        'nregions': [],
        'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
        'recregions': [fwdpy11.Region(0, 1, 1)],
        'rates': (0.0, 0.025, r),
        'gvalue': a,
        'prune_selected': False,
        'demography': demography
    }
    params = fwdpy11.ModelParams(**p)
    rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
    pop = fwdpy11.DiploidPopulation(N, 1.0)
    return params, rng, pop
Beispiel #7
0
    def setUpClass(self):
        # TODO add neutral variants
        self.N = 1000
        self.demography = np.array([self.N] * self.N, dtype=np.uint32)
        self.rho = 1.
        self.theta = 100.
        self.nreps = 500
        self.mu = self.theta / (4 * self.N)
        self.r = self.rho / (4 * self.N)

        self.GSS = fwdpy11.GSS(VS=1, opt=0)
        a = fwdpy11.Additive(2.0, self.GSS)
        self.p = {
            'nregions': [],
            'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
            'recregions': [fwdpy11.Region(0, 1, 1)],
            'rates': (0.0, 0.025, self.r),
            'gvalue': a,
            'prune_selected': False,
            'demography': self.demography
        }
        self.params = fwdpy11.ModelParams(**self.p)
        self.rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
        self.pop = fwdpy11.DiploidPopulation(self.N, 1.0)
        self.all_samples = [i for i in range(2 * self.N)]
        fwdpy11.evolvets(self.rng, self.pop, self.params, 100)
        self.dm = fwdpy11.data_matrix_from_tables(self.pop.tables,
                                                  self.all_samples, True, True)
        self.neutral = np.array(self.dm.neutral)
        self.npos = np.array(self.dm.neutral.positions)
        self.selected = np.array(self.dm.selected)
        self.spos = np.array(self.dm.selected.positions)
Beispiel #8
0
    def testPopGenSim(self):
        N = 1000
        demography = np.array([N] * 10 * N, dtype=np.uint32)
        rho = 1.
        r = rho / (4 * N)

        a = fwdpy11.Multiplicative(2.0)
        p = {
            'nregions': [],
            'sregions': [fwdpy11.ExpS(0, 1, 1, 0.01)],
            'recregions': [fwdpy11.Region(0, 1, 1)],
            'rates': (0.0, 0.00005, r),
            'gvalue': a,
            'prune_selected': True,
            'demography': demography
        }
        params = fwdpy11.ModelParams(**p)
        rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
        pop = fwdpy11.DiploidPopulation(N, 1.0)
        fwdpy11.evolvets(rng, pop, params, 100, track_mutation_counts=True)
        mc = fwdpy11.count_mutations(pop.tables, pop.mutations,
                                     [i for i in range(2 * pop.N)])
        assert len(pop.fixations) > 0, "Test is meaningless without fixations"
        fixations = np.where(mc == 2 * pop.N)[0]
        self.assertEqual(len(fixations), 0)

        # Brute-force calculation of fixations
        brute_force = np.zeros(len(pop.mutations), dtype=np.int32)
        for g in pop.haploid_genomes:
            if g.n > 0:
                for k in g.smutations:
                    brute_force[k] += g.n

        self.assertTrue(np.array_equal(brute_force, mc))
        self.assertTrue(np.array_equal(brute_force, pop.mcounts))
def evolve_snowdrift(args):
    """
    We write the function taking a tuple
    out of habit, simplifying later
    integration with multiprocessing or
    concurrent.futures.
    """
    N, seed = args
    # Construct as single-deme object
    # with N diploids
    pop = fp11.DiploidPopulation(N)
    # Initialize a random number generator
    rng = fp11.GSLrng(seed)
    p = {
        'sregions': [fp11.ExpS(0, 1, 1, -0.1, 1.0)],
        'recregions': [fp11.Region(0, 1, 1)],
        'nregions': [],
        'gvalue': snowdrift.DiploidSnowdrift(0.2, -0.2, 1, -2),
        # evolve for 100 generations so that unit tests are
        # fast
        'demography': np.array([N] * 100, dtype=np.uint32),
        'rates': (0.0, 0.0025, 0.001),
        'prune_selected': False
    }
    params = fwdpy11.ModelParams(**p)
    sampler = SamplePhenotypes(params.gvalue)
    fp11.evolve_genomes(rng, pop, params, sampler)
    # return our pop
    return pop
Beispiel #10
0
def set_up_quant_trait_model():
    N = 1000
    demography = np.array([N] * 10 * N, dtype=np.uint32)
    rho = 1000.
    r = rho / (4 * N)

    timepoints = np.array([0], dtype=np.uint32)
    ntraits = 4
    optima = np.array(np.zeros(len(timepoints) * ntraits))
    optima = optima.reshape((len(timepoints), ntraits))
    GSSmo = fwdpy11.MultivariateGSSmo(timepoints, optima, 1)
    cmat = np.identity(ntraits)
    np.fill_diagonal(cmat, 0.1)
    a = fwdpy11.StrictAdditiveMultivariateEffects(ntraits, 0, GSSmo)
    p = {
        'nregions': [],
        'sregions': [fwdpy11.MultivariateGaussianEffects(0, 1, 1, cmat)],
        'recregions': [fwdpy11.Region(0, 1, 1)],
        'rates': (0.0, 0.001, r),
        'gvalue': a,
        'prune_selected': False,
        'demography': demography
    }
    params = fwdpy11.ModelParams(**p)
    rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
    pop = fwdpy11.DiploidPopulation(N, 1.0)
    return params, rng, pop, ntraits
Beispiel #11
0
def evolve_and_return(args):
    """
    This function runs our simulation.
    The input arguments come in a tuple,
    which is required by many of Python's
    functions for execution in separate processes.

    For this function, the arguments are the population
    size and a random number seed.
    """
    from fwdpy11 import Multiplicative
    N, seed = args
    # Construct as single-deme object
    # with N diploids
    pop = fp11.DiploidPopulation(N)
    theta = 100.0
    # Initialize a random number generator
    rng = fp11.GSLrng(seed)
    p = fp11ez.mslike(pop,
                      simlen=100,
                      rates=(theta / float(4 * pop.N), 1e-3,
                             theta / float(4 * pop.N)))
    p['gvalue'] = Multiplicative(2.)
    params = fp11.ModelParams(**p)
    fp11.evolve_genomes(rng, pop, params)
    # The population is picklable, and so
    # we can return it from another process
    return pop
Beispiel #12
0
    def setUpClass(self):
        class CountSamplesPerTimePoint(object):
            def __init__(self):
                self.sample_timepoints = []
                self.sample_sizes = []
                self.timepoint_seen = {}

            def __call__(self, pop):
                assert len(pop.tables.preserved_nodes)//2 ==  \
                    len(pop.ancient_sample_metadata)
                # Get the most recent ancient samples
                # and record their number.  We do this
                # by a "brute-force" approach
                for t, n, m in pop.sample_timepoints(False):
                    if t not in self.timepoint_seen:
                        self.timepoint_seen[t] = 1
                    else:
                        self.timepoint_seen[t] += 1
                    if t not in self.sample_timepoints:
                        self.sample_timepoints.append(t)
                        self.sample_sizes.append(len(n) // 2)

                    # simplify to each time point
                    tables, idmap = fwdpy11.simplify_tables(pop.tables, n)
                    for ni in n:
                        assert idmap[ni] != fwdpy11.NULL_NODE
                        assert tables.nodes[idmap[ni]].time == t

        self.N = 1000
        self.demography = np.array([self.N] * 101, dtype=np.uint32)
        self.rho = 1.
        self.r = self.rho / (4 * self.N)

        self.GSS = fwdpy11.GSS(VS=1, opt=0)
        a = fwdpy11.Additive(2.0, self.GSS)
        self.p = {
            'nregions': [],
            'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
            'recregions': [fwdpy11.Region(0, 1, 1)],
            'rates': (0.0, 0.025, self.r),
            'gvalue': a,
            'prune_selected': False,
            'demography': self.demography
        }
        self.params = fwdpy11.ModelParams(**self.p)
        self.rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
        self.pop = fwdpy11.DiploidPopulation(self.N, 1.0)
        self.all_samples = [i for i in range(2 * self.N)]
        self.ancient_sample_recorder = \
            fwdpy11.RandomAncientSamples(seed=42,
                                         samplesize=10,
                                         timepoints=[i for i in range(1, 101)])
        self.resetter = CountSamplesPerTimePoint()
        fwdpy11.evolvets(self.rng,
                         self.pop,
                         self.params,
                         5,
                         recorder=self.ancient_sample_recorder,
                         post_simplification_recorder=self.resetter)
Beispiel #13
0
 def testMutationLookupTable(self):
     params = fwdpy11.ModelParams(**self.pdict)
     fwdpy11.evolve_genomes(self.rng, self.pop, params)
     lookup = self.pop.mut_lookup
     for i in range(len(self.pop.mcounts)):
         if self.pop.mcounts[i] > 0:
             self.assertTrue(self.pop.mutations[i].pos in lookup)
             self.assertTrue(i in lookup[self.pop.mutations[i].pos])
 def setUp(self):
     self.pop = fwdpy11.DiploidPopulation(1000)
     self.pdict = fwdpy11.ezparams.mslike(self.pop,
                                          dfe=fwdpy11.ExpS(0, 1, 1, -0.05),
                                          pneutral=0.95,
                                          simlen=10)
     self.pdict['gvalue'] = ca.additive()
     self.rng = fwdpy11.GSLrng(42)
     self.params = fwdpy11.ModelParams(**self.pdict)
Beispiel #15
0
 def testParentalData(self):
     params = fwdpy11.ModelParams(**self.pdict)
     fwdpy11.evolve_genomes(self.rng, self.pop, params)
     parents = [i.parents for i in self.pop.diploid_metadata]
     for i in parents:
         self.assertTrue(i is not None)
         self.assertTrue(len(i) == 2)
         self.assertTrue(i[0] < self.pop.N)
         self.assertTrue(i[1] < self.pop.N)
Beispiel #16
0
 def testMutationIndices(self):
     params = fwdpy11.ModelParams(**self.pdict)
     fwdpy11.evolve_genomes(self.rng, self.pop, params)
     lookup = self.pop.mut_lookup
     for key, val in lookup.items():
         indexes = self.pop.mutation_indexes(key)
         self.assertTrue(indexes is not None)
         for i in indexes:
             self.assertTrue(i in val)
Beispiel #17
0
 def testPopGenSimWithPruning(self):
     import fwdpy11
     import numpy as np
     self.p['prune_selected'] = True
     params = fwdpy11.ModelParams(**self.p)
     fwdpy11.evolve_genomes(self.rng, self.pop, params)
     assert len(
         self.pop.fixations) > 0, "Test is meaningless without fixations"
     mc = np.array(self.pop.mcounts)
     self.assertEqual(len(np.where(mc == 2 * self.pop.N)[0]), 0)
 def setUp(self):
     self.pop = fwdpy11.DiploidPopulation(1000)
     self.pdict = fwdpy11.ezparams.mslike(self.pop,
                                          dfe=fwdpy11.ConstantS(
                                              0, 1, 1, -0.05, 0.05),
                                          pneutral=0.95,
                                          simlen=10)
     self.pdict['gvalue'] = general.GeneralW()
     self.rng = fwdpy11.GSLrng(42)
     self.params = fwdpy11.ModelParams(**self.pdict)
Beispiel #19
0
def runsim(argtuple):
    seed = argtuple

    rng = fwdpy11.GSLrng(seed)

    pdict = {
        'gvalue':
        fwdpy11.Multiplicative(2.),
        'rates': (0., U / 2., R),  # The U/2. is from their eqn. 2.
        'nregions': [],
        'sregions': [
            fwdpy11.ConstantS(0, 1. / 3., 1, -0.02, 1.),
            fwdpy11.ConstantS(2. / 3., 1., 1, -0.02, 1.)
        ],
        'recregions':
        [fwdpy11.Region(0, 1. / 3., 1),
         fwdpy11.Region(2. / 3., 1., 1)],
        'demography':
        np.array([N] * 20 * N, dtype=np.uint32)
    }
    params = fwdpy11.ModelParams(**pdict)

    pop = fwdpy11.DiploidPopulation(N, GENOME_LENGTH)

    fwdpy11.evolvets(rng, pop, params, 100, suppress_table_indexing=True)

    rdips = np.random.choice(N, NSAM, replace=False)
    md = np.array(pop.diploid_metadata, copy=False)
    rdip_nodes = md['nodes'][rdips].flatten()
    nodes = np.array(pop.tables.nodes, copy=False)
    # Only visit trees spanning the
    # mutation-free segment of the genome
    tv = fwdpy11.TreeIterator(pop.tables,
                              rdip_nodes,
                              begin=1. / 3.,
                              end=2. / 3.)
    plist = np.zeros(len(nodes), dtype=np.int8)
    sum_pairwise_tmrca = 0
    for t in tv:
        for i in range(len(rdip_nodes) - 1):
            u = rdip_nodes[i]
            while u != fwdpy11.NULL_NODE:
                plist[u] = 1
                u = t.parent(u)
            for j in range(i + 1, len(rdip_nodes)):
                u = rdip_nodes[j]
                while u != fwdpy11.NULL_NODE:
                    if plist[u] == 1:
                        sum_pairwise_tmrca += 2 * \
                            (pop.generation-nodes['time'][u])
                        u = fwdpy11.NULL_NODE
                    else:
                        u = t.parent(u)
            plist.fill(0)
    return 2 * sum_pairwise_tmrca / (len(rdip_nodes) * (len(rdip_nodes) - 1))
Beispiel #20
0
 def setUp(self):
     self.pop = fwdpy11.DiploidPopulation(1000, 1.0)
     p = {'nregions': [],  # No neutral mutations -- add them later!
          'gvalue': fwdpy11.Additive(2.0),
          'sregions': [fwdpy11.ExpS(0, 1, 1, -0.1)],
          'recregions': [fwdpy11.Region(0, 1, 1)],
          'rates': (0.0, 1e-3, 1e-3),
          # Keep mutations at frequency 1 in the pop if they affect fitness.
          'prune_selected': False,
          'demography':  np.array([1000]*10000, dtype=np.uint32)
          }
     self.params = fwdpy11.ModelParams(**p)
Beispiel #21
0
def runsim(args, simseed, npseed):
    dg = demes.load(args.yaml)

    final_demes = get_final_demes(dg)

    demog = fwdpy11.discrete_demography.from_demes(dg, burnin=args.burnin)

    final_deme_ids = sorted([
        i for i in demog.metadata["deme_labels"]
        if demog.metadata["deme_labels"][i] in final_demes
    ])

    initial_sizes = [
        demog.metadata["initial_sizes"][i]
        for i in sorted(demog.metadata["initial_sizes"].keys())
    ]
    recrate = RHO / (4.0 * initial_sizes[0])

    pdict = {
        "nregions": [],
        "sregions": [],
        "recregions": [fwdpy11.PoissonInterval(0, 1, recrate)],
        "gvalue": fwdpy11.Multiplicative(2.0),
        "rates": (0.0, 0.0, None),
        "simlen": demog.metadata["total_simulation_length"],
        "demography": demog,
    }
    params = fwdpy11.ModelParams(**pdict)
    pop = fwdpy11.DiploidPopulation(initial_sizes, 1.0)

    # FIXME: need seed as input argument to this fxn
    rng = fwdpy11.GSLrng(simseed)
    np.random.seed(npseed)

    fwdpy11.evolvets(rng, pop, params, 100)

    nmuts = fwdpy11.infinite_sites(rng, pop, THETA / (4.0 * initial_sizes[0]))

    md = np.array(pop.diploid_metadata, copy=False)
    sample_nodes = []
    for i in final_deme_ids:
        w = np.where(md["deme"] == i)
        s = np.random.choice(w[0], args.nsam, replace=False)
        sample_nodes.append(md["nodes"][s].flatten())

    fs = pop.tables.fs(sample_nodes)

    return fs
Beispiel #22
0
def set_up_standard_pop_gen_model():
    """
    For this sort of model, when mutations fix, they are
    removed from the simulation, INCLUDING THE TREE
    SEQUENCES. The fact of their existence gets
    recorded in pop.fixations and pop.fixation_times
    """
    # TODO add neutral variants
    N = 1000
    demography = np.array([N] * 10 * N, dtype=np.uint32)
    rho = 1.
    # theta = 100.
    # nreps = 500
    # mu = theta/(4*N)
    r = rho / (4 * N)

    a = fwdpy11.Multiplicative(2.0)
    pselected = 1e-3
    p = {
        'nregions': [],
        'sregions': [
            fwdpy11.GammaS(0,
                           1,
                           1. - pselected,
                           mean=-5,
                           shape=1,
                           scaling=2 * N),
            fwdpy11.ConstantS(0, 1, pselected, 1000, scaling=2 * N)
        ],
        'recregions': [fwdpy11.Region(0, 1, 1)],
        'rates': (0.0, 0.001, r),
        'gvalue':
        a,
        'prune_selected':
        True,
        'demography':
        demography
    }
    params = fwdpy11.ModelParams(**p)
    rng = fwdpy11.GSLrng(666**2)
    pop = fwdpy11.DiploidPopulation(N, 1.0)
    return params, rng, pop
Beispiel #23
0
def runsim(model, num_subsamples, nsam, seed):
    rng = fwdpy11.GSLrng(seed)
    pop = fwdpy11.DiploidPopulation(model["Nref"], model["genome_length"])
    fwdpy11.evolvets(rng, pop, fwdpy11.ModelParams(**model["pdict"]), 100)
    if model["mutations_are_neutral"] is True:
        fwdpy11.infinite_sites(rng, pop, model["theta"] / 4 / model["Nref"])
    mean_fst = 0.0
    deme_zero_fs = np.zeros(2 * args.nsam - 1)
    deme_one_fs = np.zeros(2 * args.nsam - 1)
    for _ in range(num_subsamples):
        fs = testutils.analysis_tools.tskit_fs(pop, nsam)
        fs = moments.Spectrum(fs)
        mean_fst += fs.Fst()
        deme_zero_fs += fs.marginalize([1]).data[1:-1]
        deme_one_fs += fs.marginalize([0]).data[1:-1]

    mean_fst /= num_subsamples
    deme_zero_fs /= num_subsamples
    deme_one_fs /= num_subsamples

    return mean_fst, deme_zero_fs, deme_one_fs
def runsim(args):
    """
    Run the simulation and deliver output to files.
    """
    pop = fwdpy11.DiploidPopulation(args.popsize, GENOME_LENGTH)

    rng = fwdpy11.GSLrng(args.seed)

    GSSmo = fwdpy11.GSSmo([(0, 0, args.VS),
                           (10 * args.popsize, args.opt, args.VS)])

    popsizes = [args.popsize
                ] * (10 * args.popsize + int(args.time * float(args.popsize)))
    p = {
        'nregions': [],  # No neutral mutations -- add them later!
        'gvalue': fwdpy11.Additive(2.0, GSSmo),
        'sregions': [fwdpy11.GaussianS(0, GENOME_LENGTH, 1, args.sigma)],
        'recregions': [fwdpy11.Region(0, GENOME_LENGTH, 1)],
        'rates': (0.0, args.mu, args.rho / float(4 * args.popsize)),
        # Keep mutations at frequency 1 in the pop if they affect fitness.
        'prune_selected': False,
        'demography': np.array(popsizes, dtype=np.uint32)
    }
    params = fwdpy11.ModelParams(**p)

    r = Recorder(args.record, args.preserve, args.num_ind)
    fwdpy11.evolvets(rng, pop, params, 100, r, suppress_table_indexing=True)

    with lzma.open(args.filename, 'wb') as f:
        pickle.dump(pop, f)

    if args.statfile is not None:
        stats = pd.DataFrame(r.data, columns=DATA._fields)
        # Write the statistics to an sqlite3 database,
        # which can be processed in R via dplyr.
        conn = sqlite3.connect(args.statfile)
        stats.to_sql('data', conn)
Beispiel #25
0
    def testQtraitSim(self):
        N = 1000
        demography = np.array([N] * 10 * N, dtype=np.uint32)
        rho = 1.
        r = rho / (4 * N)

        GSS = fwdpy11.GSS(VS=1, opt=1)
        a = fwdpy11.Additive(2.0, GSS)
        p = {
            'nregions': [],
            'sregions': [fwdpy11.GaussianS(0, 1, 1, 0.25)],
            'recregions': [fwdpy11.PoissonInterval(0, 1, r)],
            'rates': (0.0, 0.005, None),
            'gvalue': a,
            'prune_selected': False,
            'demography': demography
        }
        params = fwdpy11.ModelParams(**p)
        rng = fwdpy11.GSLrng(101 * 45 * 110 * 210)
        pop = fwdpy11.DiploidPopulation(N, 1.0)

        class Recorder(object):
            """ Records entire pop every 100 generations """
            def __call__(self, pop, recorder):
                if pop.generation % 100 == 0.0:
                    recorder.assign(np.arange(pop.N, dtype=np.int32))

        r = Recorder()
        fwdpy11.evolvets(rng, pop, params, 100, r)

        ancient_sample_metadata = np.array(pop.ancient_sample_metadata,
                                           copy=False)
        alive_sample_metadata = np.array(pop.diploid_metadata, copy=False)
        metadata = np.hstack((ancient_sample_metadata, alive_sample_metadata))

        nodes = np.array(pop.tables.nodes, copy=False)
        metadata_nodes = metadata['nodes'].flatten()
        metadata_node_times = nodes['time'][metadata_nodes]
        metadata_record_times = nodes['time'][metadata['nodes'][:, 0]]

        genetic_trait_values_from_sim = []
        genetic_values_from_ts = []
        for u in np.unique(metadata_node_times):
            samples_at_time_u = metadata_nodes[np.where(
                metadata_node_times == u)]
            vi = fwdpy11.VariantIterator(pop.tables, samples_at_time_u)
            sum_esizes = np.zeros(len(samples_at_time_u))
            for variant in vi:
                g = variant.genotypes
                r = variant.records[0]
                mutant = np.where(g == 1)[0]
                sum_esizes[mutant] += pop.mutations[r.key].s
            ind = int(len(samples_at_time_u) / 2)
            temp_gvalues = np.zeros(ind)
            temp_gvalues += sum_esizes[0::2]
            temp_gvalues += sum_esizes[1::2]
            genetic_values_from_ts.extend(temp_gvalues.tolist())
            genetic_trait_values_from_sim.extend(metadata['g'][np.where(
                metadata_record_times == u)[0]].tolist())

        for i, j in zip(genetic_trait_values_from_sim, genetic_values_from_ts):
            self.assertAlmostEqual(i, j)
Beispiel #26
0
    with concurrent.futures.ProcessPoolExecutor(
            max_workers=args.nworkers) as e:
        futures = {
            e.submit(runsim, model, args.num_subsamples, args.nsam, i)
            for i in seeds
        }
        for fut in concurrent.futures.as_completed(futures):
            fst, d0, d1 = fut.result()
            fsta[idx] = fst
            idx += 1
            mean_deme_zero_fs += d0
            mean_deme_one_fs += d1

    mean_deme_zero_fs /= args.nreps
    mean_deme_one_fs /= args.nreps

    with open(args.outdir + "/caption.rst", "w") as f:
        f.write(f"The initial_seed was {initial_seed}.\n")
        f.write("The model details are:\n\n::\n\n")
        mp = fwdpy11.ModelParams(**model["pdict"])
        for i in mp.asblack().split("\n"):
            f.write(f"\t{i}\n")
        f.write("\n")

    with open(args.outdir + "/fst.np", "wb") as f:
        fsta.tofile(f)
    with open(args.outdir + "/deme0.np", "wb") as f:
        mean_deme_zero_fs.tofile(f)
    with open(args.outdir + "/deme1.np", "wb") as f:
        mean_deme_one_fs.tofile(f)
Beispiel #27
0
import sys

import fwdpy11

N = int(sys.argv[1])
seed = int(sys.argv[2])

pdict = {
    "nregions": [],
    "sregions": [],
    "recregions": [],
    "rates": [0, 0, 0],
    "gvalue": fwdpy11.Multiplicative(2.0),
    "simlen": 5 * N,
}
mp = fwdpy11.ModelParams(**pdict)
pop = fwdpy11.DiploidPopulation(N, 1.0)
rng = fwdpy11.GSLrng(seed)
fwdpy11.evolvets(rng, pop, mp, 100, suppress_table_indexing=True)
ts = pop.dump_tables_to_tskit()  # Copies all data from C++ to Python
ts.dump("fwdpy11.trees")
Beispiel #28
0
 def test_nodes_after_evolution(self):
     params = fwdpy11.ModelParams(**self.pdict)
     fwdpy11.evolve_genomes(self.rng, self.pop, params)
     for i in self.pop.diploid_metadata:
         self.assertEqual(i.nodes[0], fwdpy11.NULL_NODE)
         self.assertEqual(i.nodes[1], fwdpy11.NULL_NODE)