예제 #1
0
def longsweep(logger):
    # this is equivalent to
    #
    # simuGWAS.py --initPop=ex3_init.pop --DPL=rs658054 --filename=ex3_longsweep.pop \
    #   --curAlleleFreq=1 --trajectory='forward' --scale=1 --fitness="[1,1.02,1.03]"
    #
    # This just to make this result reproducible.
    getRNG().set(seed=1345)
    #
    filename = 'ex3_longsweep.pop'
    if os.path.isfile(filename):
        if logger:
            logger.info('%s already exists. Please remove this file if you would like to regenerate an expanded population.' % filename)
        return
    else:
        if logger:
            logger.info('Simulating an expanded population %s from ex3_init.pop...' % filename)
    pop = loadPopulation('ex3_init.pop')
    pars = simuOpt.Params(simuGWAS.options, DPL=[DPL],
        curAlleleFreq=[0.99], trajectory='forward',
        trajFile='ex3_longsweep.traj',
        scale=1, fitness=[1, 1.02, 1.03])
    pop = simuGWAS.simuGWAS(pars, pop, logger=logger)
    if logger:
        logger.info('Saving expanded population to %s' % filename)
    pop.save(filename)
예제 #2
0
def expandPop(logger):
    # This is equivalent to
    #
    #  > simuGWAS.py --initPop=ex2_init.pop --DPL='["rs4491689","rs6869003"]' \
    #  --filename=ex2_expanded.pop --curAlleleFreq='[0.05, 0.15]' --trajectory='forward'  --mlSelModel='multiplicative' \
    #  --scale=1 --optimized --gui=False --fitness='[1, 0.996, 0.994, 1, 1.001, 1.005]'
    #
    # This just to make this result reproducible.
    getRNG().set(seed=1355)
    #
    filename = 'ex2_expanded.pop'
    if os.path.isfile(filename):
        if logger:
            logger.info('%s already exists. Please remove this file if you would like to regenerate an expanded population.' % filename)
        return
    else:
        if logger:
            logger.info('Simulating an expanded population from ex2_init.pop...')
    pop = loadPopulation('ex2_init.pop')
    pars = simuOpt.Params(simuGWAS.options, DPL=DPL,
        curAlleleFreq=[0.05, 0.15], trajectory='forward', 
        trajPlot='ex2_traj.pdf', mlSelModel='multiplicative',
        scale=1, fitness=[1, 0.996, 0.994, 1, 1.001, 1.005])
    pop = simuGWAS.simuGWAS(pars, pop, logger=logger)
    if logger:
        logger.info('Saving expanded population to ex2_expanded.pop')
    pop.save('ex2_expanded.pop')        
예제 #3
0
def expandPop(logger):
    # Evolve the population to a population of 50,000 individuals, without a disease model.
    #
    # > simuGWAS.py --initPop=ex1_init.pop --DPL=[] --filename=ex1_expanded_1.pop --scale=1 --optimized --dumpRec=rec.log --haploCount='(0,100)'
    # > simuGWAS.py --initPop=ex1_init.pop --DPL=[] --expandSize=25000 --filename=ex1_expanded_2.pop --scale=2 --optimized --dumpRec=rec2.log --haploCount='(0,100)'
    # > simuGWAS.py --initPop=ex1_init.pop --DPL=[] --expandSize=10000 --filename=ex1_expanded_5.pop --scale=5 --optimized --dumpRec=rec5.log --haploCount='(0,100)'
    # > simuGWAS.py --initPop=ex1_init.pop --DPL=[] --expandSize=50000 --filename=ex1_expanded_55.pop --scale=5 --optimized --dumpRec=rec55.log --haploCount='(0,100)'
    #
    from simuPOP import getRNG
    getRNG().set(seed=1355)
    #
    for scale, popSize, name in [(1, 50000, '1'), (2, 25000, '2'),
                                 (5, 10000, '5'), (5, 50000, '55')]:
        filename = 'ex1_expanded_%s.pop' % name
        if os.path.isfile(filename):
            if logger:
                logger.info(
                    '%s already exists. Please remove this file if you would like to regenerate an expanded population.'
                    % filename)
            continue
        else:
            if logger:
                logger.info(
                    'Simulating an expanded population with scaling factor %d and ending population size %d'
                    % (scale, popSize))
        pop = loadPopulation('ex1_init.pop')
        pars = simuOpt.Params(simuGWAS.options,
                              migrRate=0.0001,
                              scale=scale,
                              DPL=[],
                              expandSize=popSize,
                              dumpRec='rec%d.log' % scale,
                              haploCount=(0, 100))
        pop = simuGWAS.simuGWAS(pars, pop, logger=logger)
        if logger:
            logger.info('Saving expanded population to %s' % filename)
        pop.save(filename)
    pop.dvars().migrRate = migrRate
    pop.dvars().alleleDistInSubPop = alleleDistInSubPop
    pop.dvars().migrModel = "circular stepping stone"
    pop.dvars().recRate = recRate
    pop.dvars().numOffspring = numOffspring
    pop.dvars().numOffMode = numOffMode
    print "Saving Population to " + filename + '.' + format + '\n'
    simu.population(0).save(filename)
    return True


if __name__ == '__main__':
    # get parameters
    par = simuOpt.Params(
        options,
        '''This program simulates the evolution of a complex common disease, subject 
         to the impact of mutation, migration, recombination and population size change. 
         Click 'help' for more information about the evolutionary scenario.''',
        __doc__)
    if not par.getParam():
        sys.exit(1)
    #
    if not os.path.isdir(par.name):
        os.makedirs(par.name)
        par.saveConfig(os.path.join(par.name, par.name + '.cfg'))
    # unpack options
    (numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, endingSize,
     growthModel, burninGen, splitGen, mixingGen, endingGen, numSubPop,
     migrModel, migrRate, alleleDistInSubPop, curAlleleFreq, minMutAge,
     maxMutAge, fitness, selMultiLocusModel, mutaRate, recRate, savedGen,
     numOffspring, numOffMode, dryrun, savePop, name) = par.asList()
    #
예제 #5
0
     'validator':simuOpt.valueBetween(0, 1)
    },
    {
     'name':'falleleFreq',
     'default':0.7,
     'type':[float, long],
     'label':'Female Allele Frequency',
     'description':'Initial allele frequency in females.',
     'validator':simuOpt.valueBetween(0, 1)
    },
]



# get all parameters
par = simuOpt.Params(options, __doc__)
if not par.getParam():
    sys.exit(1)

(popSize, endGen, malleleFreq, falleleFreq) = par.asList()

# diploid population, one chromosome with 1 loci
# random mating with sex
pop = Population(size=popSize, ploidy=2, loci=[1])
pop.setVirtualSplitter(SexSplitter())

# simulation
print "p\tP00 (p^2)\tP01 (2p(1-p))\tP11 ((1-p)^2)"
pop.evolve(
    initOps = [
        InitSex(),
예제 #6
0
    initGenotype(pop, genotype=[1])
    # you can also use a PointerMutator ...
    pop.individual(0).setAllele(2, 0)
    pop.individual(0).setAllele(2, 1)
    pop.evolve(
        matingScheme=RandomMating(
            ops=[MendelianGenoTransmitter(),
                 PyOperator(func=offGen)]),
        postOps=PyOperator(func=allTwos),
    )
    return (pop.dvars().succ, pop.dvars().gen)


if __name__ == '__main__':
    pars = simuOpt.Params(
        options, '''This program mimic the evolution of the infection process
    where X- chromosome will be turn to XX. We are concerned    about 
    the speed at which all Population becomes XX. ''', __doc__)

    if not pars.getParam():
        sys.exit(1)

    # get the parameters
    N = pars.N
    rep = pars.rep

    succCount = 0
    genRecord = []
    for r in range(rep):
        print "Replicate ", r,
        (succ, gen) = simu(N)
        if succ:
예제 #7
0
                N1 = (N1_lower + N1_upper) / 2
            #print 'Controls %s has power %.2f (low: %d, high: %d)' % (tmp_cases, pp, N1_lower, N1_upper)
        #
        ret = {}
        # known cases
        ret.update(cases)
        # controls
        for ped, cnt in controls.iteritems():
            ret[ped] = int(ceil(N1) * cnt / ctrlCnt)
        return ret


if __name__ == '__main__':
    # get all parameters
    pars = simuOpt.Params(
        options,
        'A power calculator for case control association studies with know family histories',
        __doc__)
    if not pars.getParam():
        sys.exit(0)
    if pars.analysis == 'Statistical power':
        # calculate power
        print "K\tp (or genoype p)\tx (or genotype x)\tD' (or R2)\talpha\tGrr\tPower"
        for K, p, x, genoP, genoX, alpha, Grr in itertools.product(
                pars.K, pars.p, pars.x, pars.genoP, pars.genoX, pars.alpha,
                pars.Grr):
            print '%.3f\t%.3f\t%.3f\t%.2f\t%.8f\t%.2f\t%f' % \
                (K, p if genoP == 0. else genoP, x if genoX == 0. else genoX,
                        pars.Dprime if pars.Dprime == 1 else pars.R2, alpha, Grr,
                powerCalculator(mode=pars.mode, K=K, p=p, x=x,
                    Dprime=pars.Dprime, R2=pars.R2, genoP=genoP, genoX=genoX).getPower(
                Grr=Grr, cases=pars.cases, controls=pars.controls, alpha=alpha))
예제 #8
0
        ],
        gen = pars.expandGen
    )
    if logger:
        logger.info('Simulation finishes in %d seconds.' %
                    (time.time() - startTime))
    return pop


short_desc = '''This program evolves a subset of the HapMap dataset
forward in time in order to simulate case control samples with realistic
allele frequency and linkage disequilibrium structure.'''

if __name__ == '__main__':
    # get all parameters
    pars = simuOpt.Params(options, short_desc, __doc__)
    # when user click cancel ...
    if not pars.getParam():
        sys.exit(1)
    # create a logger
    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger()
    logger.info('Loading initial population from file %s. ' % pars.initPop)
    init = loadPopulation(pars.initPop)
    pop = simuGWAS(pars, init, logger)
    if pars.filename:
        logger.info('Saving expanded population to %s' % pars.filename)
        pop.vars().clear()
        pop.save(pars.filename)
    numRep:  number of replicates
    '''
    pop = Population(size=popSize, ploidy=2, loci=[lociNum])

    # initialize each individual with a different allele
    for idx, ind in enumerate(pop.individuals()):
        ind.setGenotype([idx])
    #
    simu = Simulator(pop, rep=numRep)
    simu.evolve(
        initOps=InitSex(),
        matingScheme=RandomMating(ops=Recombinator(rates=recRate)),
        postOps=[PyOperator(func=avgNumOfAncestors),
                 PyOutput('\n', reps=-1)],
        gen=gen)


if __name__ == '__main__':
    pars = simuOpt.Params(
        options,
        doc=
        'This script counts the average number of ancestors who contribute\n' +
        'their genotype to an offspring after a few generations.',
        details=__doc__)

    if not pars.getParam():
        sys.exit(0)

    simuNumOfAncestors(pars.size, pars.lociNum, pars.gen, pars.recRate,
                       pars.rep)
예제 #10
0
            #Computes the frequency of each allele at selected locus at the last generation
            Stat(alleleFreq=0, step=1),
            #output to the screen the frequency of the 4 first alleles at the selected locus
            PyEval(
                r'"%.0f\t %.3f\t %.3f\t %.3f\t %.3f\t %.3f\n" % (gen, alleleFreq[0][0], alleleFreq[0][1], alleleFreq[0][2], alleleFreq[0][3], alleleFreq[0][4])',
                step=100),
            plotter,
        ],
        # sets the last generation = Tbeforesplit+Taftersplit
        gen=Tbeforesplit + Taftersplit)
    #draw two random samples from species 1 and 2 with size Nsample1 and Nsample2
    sample = drawRandomSample(pop, sizes=[Nsample1, Nsample2])
    #write to file the content of the two random samples
    sim.utils.saveCSV(sample, filename='output.txt')
    return g


if __name__ == '__main__':
    pars = simuOpt.Params(
        options,
        doc=
        'This script simulates a speciation with variation at a selected locus under overdominant selection',
        details='__doc__')

if not pars.getParam():
    sys.exit(0)

simulate(pars.NA, pars.N1, pars.N2, pars.Tbeforesplit, pars.Taftersplit,
         pars.r2loci, pars.numLoci, pars.K_sel, pars.Mu_sel, pars.S_sel,
         pars.L_neut, pars.Mu_neut, pars.Nsample1, pars.Nsample2)
예제 #11
0
            ## Pause at any user key input (for presentation purpose)
            ## Pause(stopOnKeyStroke=1)
            SavePopulation(output='!"%s/%s-%%d.txt"%% gen' % (name, name), step=3000),
        ],
        gen=end
    )
    #
    if savePop != '':
        pop.SavePopulation(savePop)


if __name__ == '__main__':
    # get parameters
    par = simuOpt.Params(
        options,
        'This program simulates the evolution of a mono or polygenic disease using a three-stage\n'
        +
        'evolutionary scenario. The allelic spectrum at all disease susceptibility loci are recorded\n'
        + 'and plotted (if R/RPy is available).', __doc__)
    if not par.getParam():
        sys.exit(1)
    #
    if not os.path.isdir(par.name):
        os.makedirs(par.name)
        par.saveConfig(os.path.join(par.name, par.name + '.cfg'))
    #
    # unpack parameters
    (numDSL, initSpecTmp, selModelTmp, selModelAllDSL, selCoefTmp, mutaModel,
     maxAllele, mutaRateTmp, initSize, finalSize, burnin, noMigrGen, mixingGen,
     growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop,
     resume, resumeAtGen, name) = par.asList()