rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
summary = '''<h2><a name="pop_%d">Dataset %d</a></h2>\n''' \ % (popIdx, popIdx) summary += '''<h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3>\n''' \ % (popIdx, popIdx, popIdx)
|
summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx)
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or randTent method 6. return a text summary and a result list ''' # get population result = [popIdx, mu, mi, rec] logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) SavePopulation(pop, popFile) # have the population, get info ## FIZMW result.extend( [ pop.dvars().AvgFst, pop.dvars().AvgHetero]) # log file is ... summary = '''<h2><a name="pop_%d">Dataset %d</a></h2>\n''' \ % (popIdx, popIdx) summary += '''<h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3>\n''' \ % (popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # if hasRPy: (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result.extend(ldres) else: # FIXME, without RPy, ld is still obtainable. retuls.extend([]) result.extend( [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL]) # # apply penetrance and get three samples (different format) summary += "<h3>Samples using different penetrance function</h3>\n" # if we are going to save in linkage format, and specify # allele frequency from the whole population, we need to calculate them # now. (Previously, we only have data for DSL if 'Linkage' in saveFormat: Stat(pop, alleleFreq=range(pop.totNumLoci())) for p in range(len(peneFunc)): if peneFunc[p] == 'recessive': print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p])) elif peneFunc[p] == 'additive': print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p])) elif peneFunc[p] == 'custom': print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p])) # save these samples # penDir = dataDir + "/" + peneFunc[p] relDir = 'pop_%d/%s/' % (popIdx, peneFunc[p]) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[0] != None: summary += str(s[0].popSize()) + " (case-control), " if s[1] != None: summary += str(s[1].popSize()) + " (affected sibs), " if s[2] != None: summary += str(s[2].popSize()) + " (unaffected sibs) " summary += '<ul>' if 'simuPOP' in saveFormat: print "Write to simuPOP format" summary += '<li>simuPOP binary format:' if s[0] != None: # has case control binFile = penDir + "/caseControl.bin" s[0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) if s[1] != None: # has case control for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model #FIXMEresult.append(res[:int(peneFunc[p][-1])]) return (summary, result)
|
if hasRPy: (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result.extend(ldres) else: retuls.extend([])
|
(suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result.extend(ldres)
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or randTent method 6. return a text summary and a result list ''' # get population result = [popIdx, mu, mi, rec] logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) SavePopulation(pop, popFile) # have the population, get info ## FIZMW result.extend( [ pop.dvars().AvgFst, pop.dvars().AvgHetero]) # log file is ... summary = '''<h2><a name="pop_%d">Dataset %d</a></h2>\n''' \ % (popIdx, popIdx) summary += '''<h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3>\n''' \ % (popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # if hasRPy: (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result.extend(ldres) else: # FIXME, without RPy, ld is still obtainable. retuls.extend([]) result.extend( [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL]) # # apply penetrance and get three samples (different format) summary += "<h3>Samples using different penetrance function</h3>\n" # if we are going to save in linkage format, and specify # allele frequency from the whole population, we need to calculate them # now. (Previously, we only have data for DSL if 'Linkage' in saveFormat: Stat(pop, alleleFreq=range(pop.totNumLoci())) for p in range(len(peneFunc)): if peneFunc[p] == 'recessive': print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p])) elif peneFunc[p] == 'additive': print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p])) elif peneFunc[p] == 'custom': print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p])) # save these samples # penDir = dataDir + "/" + peneFunc[p] relDir = 'pop_%d/%s/' % (popIdx, peneFunc[p]) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[0] != None: summary += str(s[0].popSize()) + " (case-control), " if s[1] != None: summary += str(s[1].popSize()) + " (affected sibs), " if s[2] != None: summary += str(s[2].popSize()) + " (unaffected sibs) " summary += '<ul>' if 'simuPOP' in saveFormat: print "Write to simuPOP format" summary += '<li>simuPOP binary format:' if s[0] != None: # has case control binFile = penDir + "/caseControl.bin" s[0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) if s[1] != None: # has case control for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model #FIXMEresult.append(res[:int(peneFunc[p][-1])]) return (summary, result)
|
result.append(res)
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or randTent method 6. return a text summary and a result list ''' # get population result = [popIdx, mu, mi, rec] logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) SavePopulation(pop, popFile) # have the population, get info ## FIZMW result.extend( [ pop.dvars().AvgFst, pop.dvars().AvgHetero]) # log file is ... summary = '''<h2><a name="pop_%d">Dataset %d</a></h2>\n''' \ % (popIdx, popIdx) summary += '''<h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3>\n''' \ % (popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # if hasRPy: (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result.extend(ldres) else: # FIXME, without RPy, ld is still obtainable. retuls.extend([]) result.extend( [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL]) # # apply penetrance and get three samples (different format) summary += "<h3>Samples using different penetrance function</h3>\n" # if we are going to save in linkage format, and specify # allele frequency from the whole population, we need to calculate them # now. (Previously, we only have data for DSL if 'Linkage' in saveFormat: Stat(pop, alleleFreq=range(pop.totNumLoci())) for p in range(len(peneFunc)): if peneFunc[p] == 'recessive': print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p])) elif peneFunc[p] == 'additive': print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p])) elif peneFunc[p] == 'custom': print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p])) # save these samples # penDir = dataDir + "/" + peneFunc[p] relDir = 'pop_%d/%s/' % (popIdx, peneFunc[p]) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[0] != None: summary += str(s[0].popSize()) + " (case-control), " if s[1] != None: summary += str(s[1].popSize()) + " (affected sibs), " if s[2] != None: summary += str(s[2].popSize()) + " (unaffected sibs) " summary += '<ul>' if 'simuPOP' in saveFormat: print "Write to simuPOP format" summary += '<li>simuPOP binary format:' if s[0] != None: # has case control binFile = penDir + "/caseControl.bin" s[0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) if s[1] != None: # has case control for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model #FIXMEresult.append(res[:int(peneFunc[p][-1])]) return (summary, result)
|
|
if allParam[-3] != '': for i in range(len(allParam[3])): summary.write('<th>TDT%d</th>'%(i+1))
|
if len(allParam[-8]) > 0: for p in allParam[-8]: summary.write('<th>%s:TDT</th>'%p)
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulation</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D' between a DSL and all surrounding markers (not necessarily its cloest marker), highest D' between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D'(non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allFrq%d</th>'%(i+1)) # # has TDT? if allParam[-3] != '': for i in range(len(allParam[3])): summary.write('<th>TDT%d</th>'%(i+1)) summary.write('</tr>') # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res[0], res[0])) for i in range(1,len(res)): item = res[i] if type(item) == types.FloatType: summary.write('<td>%.3g</td>'% item) elif type(item) in [types.ListType, types.TupleType]: summary.write('<td>' + ', '.join(map(lambda x:'%.3g'%x, item))+'</td>') else: summary.write('<td>%s</td>' % str(item)) summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
b = runScriptInteractively(filename = sys.argv[1])
|
b = runScriptInteractively(locals=locals(), filename = sys.argv[1])
|
def __getattr__(self, key): return getattr(self.file, key)
|
SWIG = 'swig -O -templatereduce -shadow -python -c++ -keyword -nodefaultctor -w-503,-312,-511,-362,-383,-384,-389,-315,-525'
|
SWIG = 'swig -O -templatereduce -shadow -python -outdir src -c++ -keyword -nodefaultctor -w-503,-312,-511,-362,-383,-384,-389,-315,-525'
|
def swig_version(): ''' get the version of swig ''' fout = os.popen('swig -version') # try: version = re.match('SWIG Version\s*(\d+).(\d+).(\d+).*', fout.readlines()[1]).groups() except: print 'Can not obtain swig version, please install swig' sys.exit(1) return map(int, version)
|
SWIG = 'swig -shadow -c++ -python -keyword -w-312,-401,-503,-511,-362,-383,-384,-389,-315,-525'
|
SWIG = 'swig -shadow -c++ -python -outdir src -keyword -w-312,-401,-503,-511,-362,-383,-384,-389,-315,-525'
|
def swig_version(): ''' get the version of swig ''' fout = os.popen('swig -version') # try: version = re.match('SWIG Version\s*(\d+).(\d+).(\d+).*', fout.readlines()[1]).groups() except: print 'Can not obtain swig version, please install swig' sys.exit(1) return map(int, version)
|
'Tsting counting number of male'
|
'Testing counting number of male'
|
def testNumOfMale(self): 'Tsting counting number of male' pop = population(subPop=[200, 800]) for i in range(100): pop.individual(i,0).setSex(Male) pop.individual(i,1).setSex(Male) for i in range(100,200): pop.individual(i,0).setSex(Female) for i in range(100,800): pop.individual(i,1).setSex(Female) Stat(pop, numOfMale=1) self.assertEqual(pop.dvars().numOfMale, 200) self.assertEqual(pop.dvars().numOfFemale, 800) self.assertEqual(pop.dvars(0).numOfMale, 100) self.assertEqual(pop.dvars(0).numOfFemale, 100) self.assertEqual(pop.dvars(1).numOfMale, 100) self.assertEqual(pop.dvars(1).numOfFemale, 700)
|
'Tsting counting number of affected individuals'
|
'Testing counting number of affected individuals'
|
def testNumOfAffected(self): 'Tsting counting number of affected individuals' pop = population(subPop=[200, 800]) for i in range(100): pop.individual(i,0).setAffected(True) pop.individual(i,1).setAffected(True) for i in range(100,200): pop.individual(i,0).setAffected(False) for i in range(100,800): pop.individual(i,1).setAffected(False) Stat(pop, numOfAffected=1) self.assertEqual(pop.dvars().numOfAffected, 200) self.assertEqual(pop.dvars().numOfUnaffected, 800) self.assertEqual(pop.dvars(0).numOfAffected, 100) self.assertEqual(pop.dvars(0).numOfUnaffected, 100) self.assertEqual(pop.dvars(1).numOfAffected, 100) self.assertEqual(pop.dvars(1).numOfUnaffected, 700) self.assertEqual(pop.dvars().propOfAffected, 0.2) self.assertEqual(pop.dvars().propOfUnaffected, 0.8) self.assertEqual(pop.dvars(0).propOfAffected, 0.5) self.assertEqual(pop.dvars(0).propOfUnaffected, 0.5) self.assertEqual(pop.dvars(1).propOfAffected, 1/8.) self.assertEqual(pop.dvars(1).propOfUnaffected, 7/8.)
|
penFun = customPene(penePara)
|
penFun = custom(penePara)
|
def drawSamples(pop, peneFunc, penePara, numSample, saveFormat, dataDir, reAnalyzeOnly ): ''' get samples of different type using a penetrance function, and save samples in dataDir in saveFormat pop: population peneFunc: penetrance function name, can be recessive1 etc penePara: parameter of the penetrance function numSample: number of samples for each penetrance settings saveFormat: a list of format to save dataDir: where to save samples reAnalyzeOnly: load populations only return a report ''' # first, apply peneFunction # report = '' if peneFunc.find('recessive') == 0: # start with recessive print "Using recessive penetrance function" report += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" penFun = recessive(penePara) elif peneFunc.find('additive') == 0: # start with additive print "Using additive penetrance function" report += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" penFun = additive(penePara) elif peneFunc.find('custom') == 0: # start with custom print "Using customized penetrance function" report += "<h4>Customized penetrance function</h4>\n" penFun = customPene(penePara) # this may or may not be important. Previously, we only # set penetrance for the final genetion but linkage methods # may need penetrance info for parents as well. for i in range(0, pop.ancestralDepth()+1): # apply penetrance function to all current and ancestral generations pop.useAncestralPop(i) PyPenetrance(pop, loci=pop.dvars().DSL, func=penFun) # reset population to current generation. pop.useAncestralPop(0) # report += "<ul>" # here we are facing a problem of using which allele frequency for the sample # In reality, if it is difficult to estimate population allele frequency, # sample frequency has to be used. Otherwise, population frequency should # be used whenever possible. Here, we use population allele frequency, with only # one problem in that we need to remove frequencies at DSL (since samples do not # have DSL). af = [] Stat(pop, alleleFreq=range(pop.totNumLoci())) for x in range( pop.totNumLoci() ): if x not in pop.dvars().DSL: af.append( pop.dvars().alleleFreq[x] ) # start sampling for ns in range(numSample): report += "<li> sample %d <ul>" % (ns+1) penDir = "%s%s%s%d%s" % (dataDir, os.sep, peneFunc, ns, os.sep) # relative path used in report relDir = '%s%s%s%d%s' % (dataDir.split(os.sep)[-1], os.sep, peneFunc, ns, os.sep) # _mkdir(penDir) if reAnalyzeOnly: print "Loading sample ", ns+1, ' of ', numSample else: print "Generating sample ", ns+1, ' of ', numSample # 1. population based case control # get number of affected Stat(pop, numOfAffected=True) print "Number of affected individuals: ", pop.dvars().numOfAffected print "Number of unaffected individuals: ", pop.dvars().numOfUnaffected nCase = min(pop.dvars().numOfAffected , N/2) nControl = min(pop.dvars().numOfUnaffected, N/2) try: # if N=800, 400 case and 400 controls binFile = penDir + "caseControl.bin" if reAnalyzeOnly: try: # try to load previous sample s = [LoadPopulation(binFile)] except Exception, err: print "Can not load exisiting sample. Can not use --reAnalyzeOnly option" raise err else: s = CaseControlSample(pop, nCase, nControl) # remove DSL s[0].removeLoci(remove=pop.dvars().DSL) report += "<li> Case control sample of size %d, " % s[0].popSize() # process sample if 'simuPOP' in saveFormat: report += 'saved in simuPOP binary format:' if not reAnalyzeOnly: print "Write to simuPOP binary format" s[0].savePopulation(binFile) report += '<a href="%scaseControl.bin"> caseControl.bin</a> ' % relDir report += '</li>' except Exception, err: print "Can not draw case control sample. " print type(err), err # # 2. affected and unaffected sibpairs # this is difficult since simuPOP only has # methods to draw one kind of sibpairs and try: # get number of affected/unaffected sibpairs # There may not be enough to be sampled AffectedSibpairSample(pop, countOnly=True) nAff = min(pop.dvars().numAffectedSibpairs, N/4) print "Number of (both) affected sibpairs: ", pop.dvars().numAffectedSibpairs AffectedSibpairSample(pop, chooseUnaffected=True, countOnly=True) print "Number of unaffected sibpairs: ", pop.dvars().numAffectedSibpairs nUnaff = min(pop.dvars().numAffectedSibpairs, N/4) # generate or load sample binFile1 = penDir + "affectedSibpairs.bin" binFile2 = penDir + "unaffectedSibpairs.bin" if reAnalyzeOnly: try: affected = [LoadPopulation(binFile1) ] unaffected = [LoadPopulation(binFile2) ] except Exception, err: print "can not load sample, please do not use --reAnalyzeOnly option" raise err else: # affected = AffectedSibpairSample(pop, name='sample1', size=nAff) # now chose unaffected. These samples will not overlap # # NOTE: however, you may not be able to easily merge these two # samples since they may shared parents. # # Use another name to avoid conflict since these sampled are stored # in local namespace unaffected = AffectedSibpairSample(pop, chooseUnaffected=True, name='sample2', size=nUnaff) # remove DSL affected[0].removeLoci(remove=pop.dvars().DSL) unaffected[0].removeLoci(remove=pop.dvars().DSL) # return sample # report += "<li> Affected sibpair sample of size %d (affected) %d (unaffected)" % \ ( affected[0].popSize(), unaffected[0].popSize() ) if 'simuPOP' in saveFormat: report += ' saved in simuPOP binary format:' report += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if not reAnalyzeOnly: print "Write to simuPOP binary format" affected[0].savePopulation(binFile1) unaffected[0].savePopulation(binFile2) report += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir if 'Linkage' in saveFormat: report += ' saved in linkage format by chromosome:' linDir = penDir + "Linkage" + os.sep _mkdir(linDir) report += '<a href="%sLinkage">affected</a>, ' % relDir if not reAnalyzeOnly: print "Write to linkage format" for ch in range(0, pop.numChrom() ): SaveLinkage(pop=affected[0], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) for ch in range(0,pop.numChrom() ): SaveLinkage(pop=unaffected[0], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) report += '<a href="%sLinkage">unaffected</a>' % relDir report += '</li>' except Exception, err: print type(err) print err print "Can not draw affected sibpars." report += "</ul></li>" # save these samples report += "</ul>" return report
|
print "\nList script", proc_jobs[0] script = getScript(proc_jobs[0], options)
|
print "\nList pbs_script", proc_jobs[0] pbs_script = getScript(proc_jobs[0], options)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print >> pbs, script
|
print >> pbs, pbs_script
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print script if '$' in script:
|
print pbs_script if '$' in pbs_script:
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print 'Warning: symbol $ exists in the script, indicating unsubstituted variables' print for line in script.split():
|
print 'Warning: symbol $ exists in the pbs_script, indicating unsubstituted variables' print for line in pbs_script.split():
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
script = getScript(job, options)
|
pbs_script = getScript(job, options)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
if '$' in script and not force: print script print print 'Warning: symbol $ exists in the script, indicating unsubstituted variables' print for line in script.split():
|
if '$' in pbs_script and not force: print pbs_script print print 'Warning: symbol $ exists in the pbs_script, indicating unsubstituted variables' print for line in pbs_script.split():
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print 'Please check your script, if there is no problem, please use option -f (--force)'
|
print 'Please check your pbs_script, if there is no problem, please use option -f (--force)'
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
os.system('qsub %s.pbs' % job)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
|
def TDT(DSL, dataDir, data, epsFile, jpgFile):
|
def TDT(DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def TDT(DSL, dataDir, data, epsFile, jpgFile): ''' use TDT method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying TDT method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghTDT.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("tdt " + inputfile + ".ped\n") f.close() # run gene hunter os.system(geneHunter + " < ghTDT.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value scan = re.compile('loc(\d+)\s+- Allele \d+\s+\d+\s+\d+\s+[\d.]+\s+([\d.]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("res.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match continue res.close() except: print "Can not open result file. TDT failed" return (0,[]) # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('ghTDT.cmd') except: pass # now, we need to see how TDT works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
xlab="chromosome", ylab="-log10 p-value", type='l', axes=False)
|
xlab="chromosome", ylab="-log10 p-value", type='l', axes=False, ylim=[0.01, 5])
|
def TDT(DSL, dataDir, data, epsFile, jpgFile): ''' use TDT method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying TDT method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghTDT.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("tdt " + inputfile + ".ped\n") f.close() # run gene hunter os.system(geneHunter + " < ghTDT.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value scan = re.compile('loc(\d+)\s+- Allele \d+\s+\d+\s+\d+\s+[\d.]+\s+([\d.]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("res.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match continue res.close() except: print "Can not open result file. TDT failed" return (0,[]) # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('ghTDT.cmd') except: pass # now, we need to see how TDT works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
r.abline( h = -math.log10(0.05))
|
r.abline( h = cutoff )
|
def TDT(DSL, dataDir, data, epsFile, jpgFile): ''' use TDT method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying TDT method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghTDT.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("tdt " + inputfile + ".ped\n") f.close() # run gene hunter os.system(geneHunter + " < ghTDT.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value scan = re.compile('loc(\d+)\s+- Allele \d+\s+\d+\s+\d+\s+[\d.]+\s+([\d.]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("res.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match continue res.close() except: print "Can not open result file. TDT failed" return (0,[]) # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('ghTDT.cmd') except: pass # now, we need to see how TDT works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
def Linkage(DSL, dataDir, data, epsFile, jpgFile):
|
def Linkage(DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def Linkage(DSL, dataDir, data, epsFile, jpgFile): ''' use Linkage method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying Linkage (LOD) method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghLOD.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("single point on\n") f.write("scan pedigrees " + inputfile + ".ped\n") f.write("photo tmp.txt\n") f.write("total stat\n") f.write("q\n") f.close() # run gene hunter os.system(geneHunter + " < ghLOD.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value # position (locxx) -- Lodscore -- NPL score -- p-value -- information scan = re.compile('loc(\d+)\s+[^\s]+\s+[^\s]+\s+([^\s]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("tmp.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match #print l #print err continue res.close() except Exception, err: print type(err), err print "Can not open result file tmp.txt. LOD failed" return (0,[]) # did not get anything if minPvalue == [1]*(numLoci-1): print "Do not get any p-value, something is wrong" # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('tmp.txt') os.unlink('ghLOD.cmd') except: pass # now, we need to see how Linkage works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)",
|
r.plot(allPvalue, main="-log10(P-value) for each marker (LOD)", ylim=[0.01,5],
|
def Linkage(DSL, dataDir, data, epsFile, jpgFile): ''' use Linkage method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying Linkage (LOD) method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghLOD.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("single point on\n") f.write("scan pedigrees " + inputfile + ".ped\n") f.write("photo tmp.txt\n") f.write("total stat\n") f.write("q\n") f.close() # run gene hunter os.system(geneHunter + " < ghLOD.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value # position (locxx) -- Lodscore -- NPL score -- p-value -- information scan = re.compile('loc(\d+)\s+[^\s]+\s+[^\s]+\s+([^\s]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("tmp.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match #print l #print err continue res.close() except Exception, err: print type(err), err print "Can not open result file tmp.txt. LOD failed" return (0,[]) # did not get anything if minPvalue == [1]*(numLoci-1): print "Do not get any p-value, something is wrong" # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('tmp.txt') os.unlink('ghLOD.cmd') except: pass # now, we need to see how Linkage works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
r.abline( h = -math.log10(0.05))
|
r.abline( h = cutoff )
|
def Linkage(DSL, dataDir, data, epsFile, jpgFile): ''' use Linkage method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying Linkage (LOD) method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghLOD.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("single point on\n") f.write("scan pedigrees " + inputfile + ".ped\n") f.write("photo tmp.txt\n") f.write("total stat\n") f.write("q\n") f.close() # run gene hunter os.system(geneHunter + " < ghLOD.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value # position (locxx) -- Lodscore -- NPL score -- p-value -- information scan = re.compile('loc(\d+)\s+[^\s]+\s+[^\s]+\s+([^\s]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("tmp.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match #print l #print err continue res.close() except Exception, err: print type(err), err print "Can not open result file tmp.txt. LOD failed" return (0,[]) # did not get anything if minPvalue == [1]*(numLoci-1): print "Do not get any p-value, something is wrong" # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('tmp.txt') os.unlink('ghLOD.cmd') except: pass # now, we need to see how Linkage works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = -math.log10(0.05)) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
(suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg")
|
(suc,res) = TDT(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg")
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or Linkage method 6. return a text summary and a result dictionary ''' # get population result = {'id':popIdx, 'mu':mu, 'mi':mi, 'rec':rec} logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) # check if the population is using the same parameters as requested if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) # note that this file does not have affectedness info. SavePopulation(pop, popFile) # log file is ... summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # save Fst, Het in res result['Fst'] = pop.dvars().AvgFst result['AvgHet'] = pop.dvars().AvgHetero result['alleleFreq'] = [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL] # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # ldres has max D' on a chrom with DSL, and a chrom without DSL (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result['DpDSL'] = ldres['DpDSL'] result['DpNon'] = ldres['DpNon'] result['DDSL'] = ldres['DDSL'] result['DNon'] = ldres['DNon'] # # apply penetrance and get numSample for each sample summary += "<h3>Samples using different penetrance function</h3>\n" # if we are going to save in linkage format, and specify # allele frequency from the whole population, we need to calculate them # now. (Previously, we only have data for DSL # remove DSL from the population, if 'Linkage' in saveFormat: Stat(pop, alleleFreq=range(pop.totNumLoci())) for p in range(len(peneFunc)): if peneFunc[p] == 'recessive': print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p]), numSample) elif peneFunc[p] == 'additive': print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p]), numSample) elif peneFunc[p] == 'custom': print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p]), numSample) # for each sample for sn in range(numSample): print "Processing sample %s%d" % ( peneFunc[p], sn) # save these samples penDir = dataDir + "/" + peneFunc[p] + str(sn) relDir = 'pop_%d/%s%d/' % (popIdx, peneFunc[p], sn) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[sn][0] != None: summary += str(s[sn][0].popSize()) + " (case-control), " if s[sn][1] != None: summary += str(s[sn][1].popSize()) + " (affected sibs), " if s[sn][2] != None: summary += str(s[sn][2].popSize()) + " (unaffected sibs) " summary += '<ul>' # write samples to different format if 'simuPOP' in saveFormat: print "Write to simuPOP binary format" summary += '<li>simuPOP binary format:' if s[sn][0] != None: # has case control binFile = penDir + "/caseControl.bin" s[sn][0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[sn][1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[sn][1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[sn][2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[sn][2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: print "Write to linkage format" summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) if s[sn][1] != None: # has case control for ch in range(0, pop.numChrom() ): SaveLinkage(pop=s[sn][1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, # we can not use population frequency since samples do not have DSL #alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[sn][2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[sn][2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, #alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['TDT_%s_%d' % (peneFunc[p], sn)] = res # then the Linkage method (suc,res) = Linkage(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>LOD analysis for affected sibpair data: <a href="%s/LOD.eps">LOD.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/LOD.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['LOD_%s_%d' % (peneFunc[p], sn)] = res return (summary, result)
|
(suc,res) = Linkage(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg")
|
(suc,res) = Linkage(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg")
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or Linkage method 6. return a text summary and a result dictionary ''' # get population result = {'id':popIdx, 'mu':mu, 'mi':mi, 'rec':rec} logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) # check if the population is using the same parameters as requested if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) # note that this file does not have affectedness info. SavePopulation(pop, popFile) # log file is ... summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # save Fst, Het in res result['Fst'] = pop.dvars().AvgFst result['AvgHet'] = pop.dvars().AvgHetero result['alleleFreq'] = [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL] # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # ldres has max D' on a chrom with DSL, and a chrom without DSL (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result['DpDSL'] = ldres['DpDSL'] result['DpNon'] = ldres['DpNon'] result['DDSL'] = ldres['DDSL'] result['DNon'] = ldres['DNon'] # # apply penetrance and get numSample for each sample summary += "<h3>Samples using different penetrance function</h3>\n" # if we are going to save in linkage format, and specify # allele frequency from the whole population, we need to calculate them # now. (Previously, we only have data for DSL # remove DSL from the population, if 'Linkage' in saveFormat: Stat(pop, alleleFreq=range(pop.totNumLoci())) for p in range(len(peneFunc)): if peneFunc[p] == 'recessive': print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p]), numSample) elif peneFunc[p] == 'additive': print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p]), numSample) elif peneFunc[p] == 'custom': print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p]), numSample) # for each sample for sn in range(numSample): print "Processing sample %s%d" % ( peneFunc[p], sn) # save these samples penDir = dataDir + "/" + peneFunc[p] + str(sn) relDir = 'pop_%d/%s%d/' % (popIdx, peneFunc[p], sn) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[sn][0] != None: summary += str(s[sn][0].popSize()) + " (case-control), " if s[sn][1] != None: summary += str(s[sn][1].popSize()) + " (affected sibs), " if s[sn][2] != None: summary += str(s[sn][2].popSize()) + " (unaffected sibs) " summary += '<ul>' # write samples to different format if 'simuPOP' in saveFormat: print "Write to simuPOP binary format" summary += '<li>simuPOP binary format:' if s[sn][0] != None: # has case control binFile = penDir + "/caseControl.bin" s[sn][0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[sn][1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[sn][1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[sn][2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[sn][2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: print "Write to linkage format" summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) if s[sn][1] != None: # has case control for ch in range(0, pop.numChrom() ): SaveLinkage(pop=s[sn][1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, # we can not use population frequency since samples do not have DSL #alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[sn][2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[sn][2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, #alleleFreq=pop.dvars().alleleFreq, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['TDT_%s_%d' % (peneFunc[p], sn)] = res # then the Linkage method (suc,res) = Linkage(pop.dvars().DSL, penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>LOD analysis for affected sibpair data: <a href="%s/LOD.eps">LOD.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/LOD.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['LOD_%s_%d' % (peneFunc[p], sn)] = res return (summary, result)
|
DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p>
|
DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method, + for exceeds and - for less than cutoff value -log10(pvalue/total number of loci) ) at all relevant DSL. Other statistics include K (population prevalence), Ks (sibling recurrance risk), Ls (lambda_s, sibling recurrance ratio), P11 (P(NN | affected)), P12 (P(NS | affected)), P13 (P(SS|affected))</p>
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(allParam[-9]) > 0: for p in allParam[-9]: summary.write('<th>%s:TDT</th><th>%s:LOD</th>'%(p,p)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(allParam[-9]) > 0: for met in ['TDT', 'LOD']: for p in allParam[-9]: # penetrance for num in range(int(allParam[-6])): # samples plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.): plusMinus += '+' else: plusMinus += '-' summary.write(plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])):
|
summary.write('<td>%.2g</td>' % res['Fst']) summary.write('<td>%.2g</td>' % res['AvgHet']) summary.write('<td>%.2g</td>' % res['DpDSL']) summary.write('<td>%.2g</td>' % res['DDSL']) summary.write('<td>%.2g</td>' % res['DpNon']) summary.write('<td>%.2g</td>' % res['DNon']) for i in range(len(allParam[3])):
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(allParam[-9]) > 0: for p in allParam[-9]: summary.write('<th>%s:TDT</th><th>%s:LOD</th>'%(p,p)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(allParam[-9]) > 0: for met in ['TDT', 'LOD']: for p in allParam[-9]: # penetrance for num in range(int(allParam[-6])): # samples plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.): plusMinus += '+' else: plusMinus += '-' summary.write(plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
for met in ['TDT', 'LOD']: for p in allParam[-9]:
|
for p in allParam[-9]: summary.write('<td>%.2g</td>' % res[p+'_K']) summary.write('<td>%.2g</td>' % res[p+'_Ks']) summary.write('<td>%.2g</td>' % res[p+'_Ls']) summary.write('<td>' + ','.join( ['%.2g'%x for x in res[p+'_P11'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.2g'%x for x in res[p+'_P12'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.2g'%x for x in res[p+'_P22'] ]) + '</td>') for met in ['TDT', 'LOD']:
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(allParam[-9]) > 0: for p in allParam[-9]: summary.write('<th>%s:TDT</th><th>%s:LOD</th>'%(p,p)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(allParam[-9]) > 0: for met in ['TDT', 'LOD']: for p in allParam[-9]: # penetrance for num in range(int(allParam[-6])): # samples plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.): plusMinus += '+' else: plusMinus += '-' summary.write(plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.):
|
plusMinus = '' for pvalue in res[met+'_'+p+'_'+str(num)]: if pvalue > -math.log10(0.05/(allParam[0]*allParam[1])):
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(allParam[-9]) > 0: for p in allParam[-9]: summary.write('<th>%s:TDT</th><th>%s:LOD</th>'%(p,p)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(allParam[-9]) > 0: for met in ['TDT', 'LOD']: for p in allParam[-9]: # penetrance for num in range(int(allParam[-6])): # samples plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.): plusMinus += '+' else: plusMinus += '-' summary.write(plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
summary.write(plusMinus+'</td>')
|
summary.write('<td>'+plusMinus+'</td>')
|
def writeReport(content, allParam, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method) at all relevant DSL. </p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(allParam[3])): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(allParam[-9]) > 0: for p in allParam[-9]: summary.write('<th>%s:TDT</th><th>%s:LOD</th>'%(p,p)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.5g</td>' % res['Fst']) summary.write('<td>%.5g</td>' % res['AvgHet']) summary.write('<td>%.5g/%.5g</td>' % (res['DpDSL'], res['DpNon'])) summary.write('<td>%.5g/%.5g</td>' % (res['DDSL'], res['DNon'])) for i in range(len(allParam[3])): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(allParam[-9]) > 0: for met in ['TDT', 'LOD']: for p in allParam[-9]: # penetrance for num in range(int(allParam[-6])): # samples plusMinus = '<td>' for p in res[met+'_'+p+'_'+str(num)]: if p > -math.log10(0.01/400.): plusMinus += '+' else: plusMinus += '-' summary.write(plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
if len(traj) < max(2, minMutAge):
|
if True in [len(t) < max(2, minMutAge) for t in traj]:
|
def FreqTrajectoryMultiStochWithSubPop( curGen, numLoci, freq, NtFunc, fitness, minMutAge, maxMutAge, mode = 'uneven', ploidy=2, restartIfFail=True): ''' Simulate frequency trajectory with subpopulation structure, migration is currently ignored. The essential part of this script is to simulate the trajectory of each subpopulation independently by calling FreqTrajectoryMultiStoch with properly wrapped NtFunc function. If mode = 'even' (default) When freq is the same length of the number of loci. The allele frequency at the last generation will be multi-nomially distributed. If freq for each subpop is specified in the order of loc1-sp1, loc1-sp2, .. loc2-sp1, .... This freq will be used directly. If mode = 'uneven'. The number of disease alleles will be proportional to the interval lengths of 0 x x x 1 while x are uniform [0,1]. The distribution of interval lengths, are roughly exponential (conditional on overall length 1). ' If mode = 'none', subpop will be ignored. This script assume a single-split model of NtFunc ''' numSP = len(NtFunc(curGen)) if maxMutAge == 0: maxMutAge = endGen TurnOnDebug(DBG_GENERAL) if numSP == 1 or mode == 'none': traj = FreqTrajectoryMultiStoch( curGen=curGen, freq=freq, NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, ploidy=ploidy, restartIfFail=True) #print traj if len(traj) < max(2, minMutAge): print "Failed to generate trajectory. You may need to set a different set of parameters." print 'Info:' print 'curGen: ', curGen print 'freq: ', freq print 'begin size: ', NtFunc(0) print 'ending size: ', NtFunc(curGen) print 'fitness: ', fitness print 'minMutAge: ', minMutAge print 'maxMutAge: ', maxMutAge print 'ploidy: ', ploidy print 'restart: ', restart sys.exit(1) return (traj, [curGen-len(x)+1 for x in traj], trajFunc(curGen, traj)) # other wise, do it in two stages # get the split generation. split = curGen; while(True): if len(NtFunc(split)) == 1: break split -= 1 split += 1 # set default for min/max mutage if minMutAge < curGen - split: minMutAge = split if minMutAge > maxMutAge: print "Minimal mutant age %d is larger then maximum age %d" % (minMutAge, maxMutAge) sys.exit(1) # now, NtFunc(split) has subpopulations # # for each subpopulation if len(freq) == numSP*numLoci: freqAll = freq elif len(freq) == numLoci: freqAll = [0]*(numLoci*numSP) if mode == 'even': for i in range(numLoci): wt = NtFunc(curGen) ps = sum(wt) # total allele number totNum = int(freq[i]*ps) # in subpopulations, according to population size num = rng().randMultinomialVal(totNum, [x/float(ps) for x in wt]) for sp in range(numSP): freqAll[sp+i*numSP] = num[sp]/float(wt[sp]) elif mode == 'uneven': for i in range(numLoci): wt = NtFunc(curGen) # total allele number totNum = int(freq[i]*sum(wt)) while(True): # get [ x x x x x ] while x is uniform [0,1] num = [0,1]+[rng().randUniform01() for x in range(numSP-1)] num.sort() for sp in range(numSP): freqAll[sp+i*numSP] = (num[sp+1]-num[sp])*totNum/wt[sp] if max(freqAll) < 1: break; else: print "Wrong mode parameter is used: ", mode print "Using ", mode, "distribution of alleles at the last generation" print "Frequencies at the last generation: sp0-loc0, loc1, ..., sp1-loc0,..." for sp in range(numSP): print "SP ", sp, ': ', for i in range(numLoci): print "%.3f " % freqAll[sp+i*numSP], print else: raise exceptions.ValueError("Wrong freq length") spTraj = [0]*numSP*numLoci for sp in range(numSP): print "Generting trajectory for subpopulation %d (generation %d - %d)" % (sp, split, curGen) # FreqTraj... will probe Nt for the next geneartion. def spPopSize(gen): if gen < split: return [NtFunc(split-1)[0]] else: return [NtFunc(gen)[sp]] while True: t = FreqTrajectoryMultiStoch( curGen=curGen, freq=[freqAll[sp+x*numSP] for x in range(numLoci)], NtFunc=spPopSize, fitness=fitness, minMutAge=curGen-split, maxMutAge=curGen-split, ploidy=ploidy, restartIfFail=False) # failed to generate one of the trajectory if 0 in [len(x) for x in t]: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) if 0 in [x[0] for x in t]: print "Subpop return 0 index. restart " else: break; # now spTraj has SP0: loc0,1,2..., SP1 loc 0,1,2,..., ... for i in range(numLoci): spTraj[sp+i*numSP] = t[i] # add all trajectories traj = [] for i in range(numLoci): traj.append([]) for g in range(split, curGen+1): totAllele = sum( [ spTraj[sp+i*numSP][g-split] * NtFunc(g)[sp] for sp in range(numSP) ]) traj[i].append( totAllele / sum(NtFunc(g)) ) # print "Starting allele frequency (at split) ", [traj[i][0] for i in range(numLoci)] print "Generating combined trajsctory with range: ", minMutAge, " - ", maxMutAge trajBeforeSplit = FreqTrajectoryMultiStoch( curGen=split, freq=[traj[i][0] for i in range(numLoci)], NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge-len(traj[0])+1, maxMutAge=maxMutAge-len(traj[0])+1, ploidy=ploidy, restartIfFail=True) if 1 in [len(x) for x in trajBeforeSplit]: print "Failed to generated trajectory. (Tried more than 1000 times)" sys.exit(0) def trajFuncWithSubPop(gen): if gen >= split: return [spTraj[x][gen-split] for x in range(numLoci*numSP)] else: freq = [] for tr in trajBeforeSplit: if gen < split - len(tr) + 1: freq.append( 0 ) else: freq.append( tr[ gen - (split - len(tr) + 1) ] ) return freq trajAll = [] for i in range(numLoci): trajAll.append( [] ) trajAll[i].extend(trajBeforeSplit[i]) trajAll[i].extend(traj[i][1:]) # how exactly should I return a trajectory? return (trajAll, [curGen-len(x)+1 for x in trajAll ], trajFuncWithSubPop)
|
print 'Info:'
|
print "len: ", [len(t) for t in traj]
|
def FreqTrajectoryMultiStochWithSubPop( curGen, numLoci, freq, NtFunc, fitness, minMutAge, maxMutAge, mode = 'uneven', ploidy=2, restartIfFail=True): ''' Simulate frequency trajectory with subpopulation structure, migration is currently ignored. The essential part of this script is to simulate the trajectory of each subpopulation independently by calling FreqTrajectoryMultiStoch with properly wrapped NtFunc function. If mode = 'even' (default) When freq is the same length of the number of loci. The allele frequency at the last generation will be multi-nomially distributed. If freq for each subpop is specified in the order of loc1-sp1, loc1-sp2, .. loc2-sp1, .... This freq will be used directly. If mode = 'uneven'. The number of disease alleles will be proportional to the interval lengths of 0 x x x 1 while x are uniform [0,1]. The distribution of interval lengths, are roughly exponential (conditional on overall length 1). ' If mode = 'none', subpop will be ignored. This script assume a single-split model of NtFunc ''' numSP = len(NtFunc(curGen)) if maxMutAge == 0: maxMutAge = endGen TurnOnDebug(DBG_GENERAL) if numSP == 1 or mode == 'none': traj = FreqTrajectoryMultiStoch( curGen=curGen, freq=freq, NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, ploidy=ploidy, restartIfFail=True) #print traj if len(traj) < max(2, minMutAge): print "Failed to generate trajectory. You may need to set a different set of parameters." print 'Info:' print 'curGen: ', curGen print 'freq: ', freq print 'begin size: ', NtFunc(0) print 'ending size: ', NtFunc(curGen) print 'fitness: ', fitness print 'minMutAge: ', minMutAge print 'maxMutAge: ', maxMutAge print 'ploidy: ', ploidy print 'restart: ', restart sys.exit(1) return (traj, [curGen-len(x)+1 for x in traj], trajFunc(curGen, traj)) # other wise, do it in two stages # get the split generation. split = curGen; while(True): if len(NtFunc(split)) == 1: break split -= 1 split += 1 # set default for min/max mutage if minMutAge < curGen - split: minMutAge = split if minMutAge > maxMutAge: print "Minimal mutant age %d is larger then maximum age %d" % (minMutAge, maxMutAge) sys.exit(1) # now, NtFunc(split) has subpopulations # # for each subpopulation if len(freq) == numSP*numLoci: freqAll = freq elif len(freq) == numLoci: freqAll = [0]*(numLoci*numSP) if mode == 'even': for i in range(numLoci): wt = NtFunc(curGen) ps = sum(wt) # total allele number totNum = int(freq[i]*ps) # in subpopulations, according to population size num = rng().randMultinomialVal(totNum, [x/float(ps) for x in wt]) for sp in range(numSP): freqAll[sp+i*numSP] = num[sp]/float(wt[sp]) elif mode == 'uneven': for i in range(numLoci): wt = NtFunc(curGen) # total allele number totNum = int(freq[i]*sum(wt)) while(True): # get [ x x x x x ] while x is uniform [0,1] num = [0,1]+[rng().randUniform01() for x in range(numSP-1)] num.sort() for sp in range(numSP): freqAll[sp+i*numSP] = (num[sp+1]-num[sp])*totNum/wt[sp] if max(freqAll) < 1: break; else: print "Wrong mode parameter is used: ", mode print "Using ", mode, "distribution of alleles at the last generation" print "Frequencies at the last generation: sp0-loc0, loc1, ..., sp1-loc0,..." for sp in range(numSP): print "SP ", sp, ': ', for i in range(numLoci): print "%.3f " % freqAll[sp+i*numSP], print else: raise exceptions.ValueError("Wrong freq length") spTraj = [0]*numSP*numLoci for sp in range(numSP): print "Generting trajectory for subpopulation %d (generation %d - %d)" % (sp, split, curGen) # FreqTraj... will probe Nt for the next geneartion. def spPopSize(gen): if gen < split: return [NtFunc(split-1)[0]] else: return [NtFunc(gen)[sp]] while True: t = FreqTrajectoryMultiStoch( curGen=curGen, freq=[freqAll[sp+x*numSP] for x in range(numLoci)], NtFunc=spPopSize, fitness=fitness, minMutAge=curGen-split, maxMutAge=curGen-split, ploidy=ploidy, restartIfFail=False) # failed to generate one of the trajectory if 0 in [len(x) for x in t]: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) if 0 in [x[0] for x in t]: print "Subpop return 0 index. restart " else: break; # now spTraj has SP0: loc0,1,2..., SP1 loc 0,1,2,..., ... for i in range(numLoci): spTraj[sp+i*numSP] = t[i] # add all trajectories traj = [] for i in range(numLoci): traj.append([]) for g in range(split, curGen+1): totAllele = sum( [ spTraj[sp+i*numSP][g-split] * NtFunc(g)[sp] for sp in range(numSP) ]) traj[i].append( totAllele / sum(NtFunc(g)) ) # print "Starting allele frequency (at split) ", [traj[i][0] for i in range(numLoci)] print "Generating combined trajsctory with range: ", minMutAge, " - ", maxMutAge trajBeforeSplit = FreqTrajectoryMultiStoch( curGen=split, freq=[traj[i][0] for i in range(numLoci)], NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge-len(traj[0])+1, maxMutAge=maxMutAge-len(traj[0])+1, ploidy=ploidy, restartIfFail=True) if 1 in [len(x) for x in trajBeforeSplit]: print "Failed to generated trajectory. (Tried more than 1000 times)" sys.exit(0) def trajFuncWithSubPop(gen): if gen >= split: return [spTraj[x][gen-split] for x in range(numLoci*numSP)] else: freq = [] for tr in trajBeforeSplit: if gen < split - len(tr) + 1: freq.append( 0 ) else: freq.append( tr[ gen - (split - len(tr) + 1) ] ) return freq trajAll = [] for i in range(numLoci): trajAll.append( [] ) trajAll[i].extend(trajBeforeSplit[i]) trajAll[i].extend(traj[i][1:]) # how exactly should I return a trajectory? return (trajAll, [curGen-len(x)+1 for x in trajAll ], trajFuncWithSubPop)
|
if len(traj) == 0:
|
if len(traj) == 1:
|
def FreqTrajectoryMultiStochWithSubPop( curGen, numLoci, freq, NtFunc, fitness, minMutAge, maxMutAge, mode = 'uneven', ploidy=2, restartIfFail=True): ''' Simulate frequency trajectory with subpopulation structure, migration is currently ignored. The essential part of this script is to simulate the trajectory of each subpopulation independently by calling FreqTrajectoryMultiStoch with properly wrapped NtFunc function. If mode = 'even' (default) When freq is the same length of the number of loci. The allele frequency at the last generation will be multi-nomially distributed. If freq for each subpop is specified in the order of loc1-sp1, loc1-sp2, .. loc2-sp1, .... This freq will be used directly. If mode = 'uneven'. The number of disease alleles will be proportional to the interval lengths of 0 x x x 1 while x are uniform [0,1]. The distribution of interval lengths, are roughly exponential (conditional on overall length 1). ' If mode = 'none', subpop will be ignored. This script assume a single-split model of NtFunc ''' numSP = len(NtFunc(curGen)) if numSP == 1 or mode == 'none': traj = FreqTrajectoryMultiStoch( curGen=curGen, freq=freq, NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, ploidy=ploidy, restartIfFail=restartIfFail) if len(traj) == 0: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) return (traj, [curGen-len(x)+1 for x in traj], trajFunc(curGen, traj)) # other wise, do it in two stages # get the split generation. split = curGen; while(True): if len(NtFunc(split)) == 1: break split -= 1 split += 1 # set default for min/max mutage if minMutAge < curGen - split: minMutAge = split if maxMutAge == 0: maxMutAge = endGen if minMutAge > maxMutAge: print "Minimal mutant age %d is larger then maximum age %d" % (minMutAge, maxMutAge) sys.exit(1) # now, NtFunc(split) has subpopulations # # for each subpopulation if len(freq) == numSP*numLoci: freqAll = freq elif len(freq) == numLoci: freqAll = [0]*(numLoci*numSP) if mode == 'even': for i in range(numLoci): wt = NtFunc(curGen) ps = sum(wt) # total allele number totNum = int(freq[i]*ps) # in subpopulations, according to population size num = rng().randMultinomialVal(totNum, [x/float(ps) for x in wt]) for sp in range(numSP): freqAll[sp+i*numSP] = num[sp]/float(wt[sp]) elif mode == 'uneven': for i in range(numLoci): wt = NtFunc(curGen) # total allele number totNum = int(freq[i]*sum(wt)) while(True): # get [ x x x x x ] while x is uniform [0,1] num = [0,1]+[rng().randUniform01() for x in range(numSP-1)] num.sort() for sp in range(numSP): freqAll[sp+i*numSP] = (num[sp+1]-num[sp])*totNum/wt[sp] if max(freqAll) < 1: break; else: print "Wrong mode parameter is used: ", mode print "Using ", mode, "distribution of alleles at the last generation" print "Frequencies at the last generation: sp0-loc0, loc1, ..., sp1-loc0,..." for sp in range(numSP): print "SP ", sp, ': ', for i in range(numLoci): print "%.3f " % freqAll[sp+i*numSP], print else: raise exceptions.ValueError("Wrong freq length") spTraj = [0]*numSP*numLoci for sp in range(numSP): print "Generting trajectory for subpopulation %d (generation %d - %d)" % (sp, split, curGen) # FreqTraj... will probe Nt for the next geneartion. def spPopSize(gen): if gen < split: return [NtFunc(split-1)[0]] else: return [NtFunc(gen)[sp]] while True: t = FreqTrajectoryMultiStoch( curGen=curGen, freq=[freqAll[sp+x*numSP] for x in range(numLoci)], NtFunc=spPopSize, fitness=fitness, minMutAge=curGen-split, maxMutAge=curGen-split, ploidy=ploidy, restartIfFail=False) # failed to generate one of the trajectory if 0 in [len(x) for x in t]: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) if 0 in [x[0] for x in t]: print "Subpop return 0 index. restart " else: break; # now spTraj has SP0: loc0,1,2..., SP1 loc 0,1,2,..., ... for i in range(numLoci): spTraj[sp+i*numSP] = t[i] # add all trajectories traj = [] for i in range(numLoci): traj.append([]) for g in range(split, curGen+1): totAllele = sum( [ spTraj[sp+i*numSP][g-split] * NtFunc(g)[sp] for sp in range(numSP) ]) traj[i].append( totAllele / sum(NtFunc(g)) ) # print "Starting allele frequency (at split) ", [traj[i][0] for i in range(numLoci)] print "Generating combined trajsctory with range: ", minMutAge, " - ", maxMutAge trajBeforeSplit = FreqTrajectoryMultiStoch( curGen=split, freq=[traj[i][0] for i in range(numLoci)], NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge-len(traj[0])+1, maxMutAge=maxMutAge-len(traj[0])+1, ploidy=ploidy, restartIfFail=True) if 1 in [len(x) for x in trajBeforeSplit]: print "Failed to generated trajectory. (Tried more than 1000 times)" sys.exit(0) def trajFuncWithSubPop(gen): if gen >= split: return [spTraj[x][gen-split] for x in range(numLoci*numSP)] else: freq = [] for tr in trajBeforeSplit: if gen < split - len(tr) + 1: freq.append( 0 ) else: freq.append( tr[ gen - (split - len(tr) + 1) ] ) return freq trajAll = [] for i in range(numLoci): trajAll.append( [] ) trajAll[i].extend(trajBeforeSplit[i]) trajAll[i].extend(traj[i][1:]) # how exactly should I return a trajectory? return (trajAll, [curGen-len(x)+1 for x in trajAll ], trajFuncWithSubPop)
|
if maxMutAge == 0: maxMutAge = endGen
|
def FreqTrajectoryMultiStochWithSubPop( curGen, numLoci, freq, NtFunc, fitness, minMutAge, maxMutAge, mode = 'uneven', ploidy=2, restartIfFail=True): ''' Simulate frequency trajectory with subpopulation structure, migration is currently ignored. The essential part of this script is to simulate the trajectory of each subpopulation independently by calling FreqTrajectoryMultiStoch with properly wrapped NtFunc function. If mode = 'even' (default) When freq is the same length of the number of loci. The allele frequency at the last generation will be multi-nomially distributed. If freq for each subpop is specified in the order of loc1-sp1, loc1-sp2, .. loc2-sp1, .... This freq will be used directly. If mode = 'uneven'. The number of disease alleles will be proportional to the interval lengths of 0 x x x 1 while x are uniform [0,1]. The distribution of interval lengths, are roughly exponential (conditional on overall length 1). ' If mode = 'none', subpop will be ignored. This script assume a single-split model of NtFunc ''' numSP = len(NtFunc(curGen)) if numSP == 1 or mode == 'none': traj = FreqTrajectoryMultiStoch( curGen=curGen, freq=freq, NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, ploidy=ploidy, restartIfFail=restartIfFail) if len(traj) == 0: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) return (traj, [curGen-len(x)+1 for x in traj], trajFunc(curGen, traj)) # other wise, do it in two stages # get the split generation. split = curGen; while(True): if len(NtFunc(split)) == 1: break split -= 1 split += 1 # set default for min/max mutage if minMutAge < curGen - split: minMutAge = split if maxMutAge == 0: maxMutAge = endGen if minMutAge > maxMutAge: print "Minimal mutant age %d is larger then maximum age %d" % (minMutAge, maxMutAge) sys.exit(1) # now, NtFunc(split) has subpopulations # # for each subpopulation if len(freq) == numSP*numLoci: freqAll = freq elif len(freq) == numLoci: freqAll = [0]*(numLoci*numSP) if mode == 'even': for i in range(numLoci): wt = NtFunc(curGen) ps = sum(wt) # total allele number totNum = int(freq[i]*ps) # in subpopulations, according to population size num = rng().randMultinomialVal(totNum, [x/float(ps) for x in wt]) for sp in range(numSP): freqAll[sp+i*numSP] = num[sp]/float(wt[sp]) elif mode == 'uneven': for i in range(numLoci): wt = NtFunc(curGen) # total allele number totNum = int(freq[i]*sum(wt)) while(True): # get [ x x x x x ] while x is uniform [0,1] num = [0,1]+[rng().randUniform01() for x in range(numSP-1)] num.sort() for sp in range(numSP): freqAll[sp+i*numSP] = (num[sp+1]-num[sp])*totNum/wt[sp] if max(freqAll) < 1: break; else: print "Wrong mode parameter is used: ", mode print "Using ", mode, "distribution of alleles at the last generation" print "Frequencies at the last generation: sp0-loc0, loc1, ..., sp1-loc0,..." for sp in range(numSP): print "SP ", sp, ': ', for i in range(numLoci): print "%.3f " % freqAll[sp+i*numSP], print else: raise exceptions.ValueError("Wrong freq length") spTraj = [0]*numSP*numLoci for sp in range(numSP): print "Generting trajectory for subpopulation %d (generation %d - %d)" % (sp, split, curGen) # FreqTraj... will probe Nt for the next geneartion. def spPopSize(gen): if gen < split: return [NtFunc(split-1)[0]] else: return [NtFunc(gen)[sp]] while True: t = FreqTrajectoryMultiStoch( curGen=curGen, freq=[freqAll[sp+x*numSP] for x in range(numLoci)], NtFunc=spPopSize, fitness=fitness, minMutAge=curGen-split, maxMutAge=curGen-split, ploidy=ploidy, restartIfFail=False) # failed to generate one of the trajectory if 0 in [len(x) for x in t]: print "Failed to generate trajectory. You may need to set a different set of parameters." sys.exit(1) if 0 in [x[0] for x in t]: print "Subpop return 0 index. restart " else: break; # now spTraj has SP0: loc0,1,2..., SP1 loc 0,1,2,..., ... for i in range(numLoci): spTraj[sp+i*numSP] = t[i] # add all trajectories traj = [] for i in range(numLoci): traj.append([]) for g in range(split, curGen+1): totAllele = sum( [ spTraj[sp+i*numSP][g-split] * NtFunc(g)[sp] for sp in range(numSP) ]) traj[i].append( totAllele / sum(NtFunc(g)) ) # print "Starting allele frequency (at split) ", [traj[i][0] for i in range(numLoci)] print "Generating combined trajsctory with range: ", minMutAge, " - ", maxMutAge trajBeforeSplit = FreqTrajectoryMultiStoch( curGen=split, freq=[traj[i][0] for i in range(numLoci)], NtFunc=NtFunc, fitness=fitness, minMutAge=minMutAge-len(traj[0])+1, maxMutAge=maxMutAge-len(traj[0])+1, ploidy=ploidy, restartIfFail=True) if 1 in [len(x) for x in trajBeforeSplit]: print "Failed to generated trajectory. (Tried more than 1000 times)" sys.exit(0) def trajFuncWithSubPop(gen): if gen >= split: return [spTraj[x][gen-split] for x in range(numLoci*numSP)] else: freq = [] for tr in trajBeforeSplit: if gen < split - len(tr) + 1: freq.append( 0 ) else: freq.append( tr[ gen - (split - len(tr) + 1) ] ) return freq trajAll = [] for i in range(numLoci): trajAll.append( [] ) trajAll[i].extend(trajBeforeSplit[i]) trajAll[i].extend(traj[i][1:]) # how exactly should I return a trajectory? return (trajAll, [curGen-len(x)+1 for x in trajAll ], trajFuncWithSubPop)
|
|
introFree, selFreeIntensity, initSize, endingSize, growthModel,
|
initSize, endingSize, growthModel,
|
def simuComplexDisease(numChrom, numLoci, markerType, DSLafter, DSLdistTmp, introFree, selFreeIntensity, initSize, endingSize, growthModel, burninGen, splitGen, mixingGen, endingGen, numSubPop, migrModel, migrRate, alleleDistInSubPop, curAlleleFreqTmp, minMutAge, maxMutAge, fitnessTmp, mlSelModelTmp, mutaRate, recRate, savedGen, numOffspring, numOffMode, simuAge, dryrun, savePop, filename, format): ''' run a simulation of complex disease with given parameters. ''' ### ### CHECK PARAMETERS ### if initSize < len(DSLafter): raise exceptions.ValueError("Initial population size is too small. (Less than number of DSL)") # expand .5 -> [0.5, 0.5...] if len(DSLdistTmp) == 1: DSLdist = DSLdistTmp * len(DSLafter) else: DSLdist = DSLdistTmp if len( DSLafter ) != len(DSLdist): raise exceptions.ValueError("Please specify DSL distance for each DSL.") numDSL = len(DSLafter) if burninGen > splitGen or splitGen > mixingGen or splitGen > endingGen: raise exceptions.ValueError("Generations should in the order of burnin, split, mixing and ending") # curAlleleFreq expand 0.5 -> [0.5,0.5,...] if len(curAlleleFreqTmp) == 1: curAlleleFreq = curAlleleFreqTmp * len(DSLafter) elif len(curAlleleFreqTmp) == len(DSLafter): curAlleleFreq = curAlleleFreqTmp else: raise exceptions.ValueError("min allele frequency should be either a number or a list\n" + " of the same length as DSLafter") # fitness if mlSelModelTmp == 'none': fitness = [] elif mlSelModelTmp == 'interaction': if numDSL == 1: raise exceptions.ValueError("Interaction model can only be used with more than one DSL"); if len(fitnessTmp) != 3**numDSL: raise exceptions.ValueError("Please specify 3^n fitness values for n DSL"); fitness = fitnessTmp else: if fitnessTmp == []: # neutral process fitness = [1,1,1]*numDSL else: # for a single DSL if len(fitnessTmp) == 3: fitness = fitnessTmp*numDSL elif len(fitnessTmp) != numDSL*3: raise exceptions.ValueError("Please specify fitness for each DSL") else: fitness = fitnessTmp # number of offspring if numOffMode == 'geometric' and numOffspring > 1: raise exceptions.ValueError("numOffspring is p for a geometric distribution when numOffMode='geometric'. It should be elss than 1.") ### ### simulating population frequency ### print '\n\nSimulating trajectory of allele frequencies' # 1. define population size function def popSizeFunc(gen, curSize=[]): if gen < burninGen: return [initSize] if growthModel == 'linear': inc = (endingSize-initSize)/float(endingGen-burninGen) if gen < splitGen: return [int(initSize+inc*(gen-burninGen))] else: return [int(initSize+inc*(gen-burninGen))/numSubPop]*numSubPop else: # exponential rate = (math.log(endingSize)-math.log(initSize))/(endingGen-burninGen) if gen < splitGen: return [int(initSize*math.exp((gen-burninGen)*rate))] else: return [int(initSize*math.exp((gen-burninGen)*rate)/numSubPop)]*numSubPop # 2. simulating allele frequency trajectory if maxMutAge == 0: maxMutAge = endingGen elif maxMutAge < minMutAge: raise exceptions.ValueError('maxMutAge needs to be greater than minMutAge.') elif maxMutAge > endingGen: print 'maxMutAge should be smaller than endingGen, set it to endingGen.' maxMutAge = endingGen # this is defined in simuUtil, a wrapper for # FreqTrajectoryMultiStoch if simuAge > 0: mutantAges = [] for i in range(simuAge): (traj, introGens, trajFunc) = FreqTrajectoryMultiStochWithSubPop( curGen=endingGen, numLoci=len(DSLafter), freq=curAlleleFreq, NtFunc=popSizeFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, mode=alleleDistInSubPop, restartIfFail=True) mutantAges.append([len(x) for x in traj]) print "Simulated trajectory length:" for i,age in enumerate(mutantAges): print 'simu %3d:' % i, ', '.join(['%6d' % x for x in age]) mean = [sum([x[col] for x in mutantAges])*1./simuAge for col in range(len(DSLafter))] print "Mean: ", ', '.join(['%6.1f' % x for x in mean]) sys.exit(0) (traj, introGens, trajFunc) = FreqTrajectoryMultiStochWithSubPop( curGen=endingGen, numLoci=len(DSLafter), freq=curAlleleFreq, NtFunc=popSizeFunc, fitness=fitness, minMutAge=minMutAge, maxMutAge=maxMutAge, mode=alleleDistInSubPop, restartIfFail=True) # # 3. save and plot the simulation scenario tfile = open(filename+'.traj', 'w') tfile.write('Simulated trajectories:\n') for t in traj: tfile.write(', '.join([str(x) for x in t ]) + '\n') tfile.write('Observed allele frequency (generation, population size, allele frequencies)\n') tfile.close() print '\n\nTrajectories simulated successfully. Their lengths are %s.\n Check %s.eps for details. \n\n' \ % ( ', '.join([ str(len(x)) for x in traj]), filename) ### ### translate numChrom, numLoci, DSLafterLoci to ### loci, lociPos, DSL, nonDSL in the usual index ### (count DSL along with markers) ### if markerType == 'microsatellite': maxAle = 99 # max allele else: maxAle = 1 # SNP (0 and 1) numDSL = len(DSLafter) if len(DSLdist) != numDSL: raise exceptions.ValueError("--DSL and --DSLloc has different length.") # real indices of DSL DSL = list(DSLafter) for i in range(0,numDSL): DSL[i] += i+1 # adjust loci and lociPos loci = [0]*numChrom lociPos = [] i = 0 # current absolute locus j = 0 # current DSL for ch in range(0, numChrom): lociPos.append([]) for loc in range(0,numLoci): # DSL after original loci indices if j < numDSL and i == DSLafter[j]: loci[ch] += 2 lociPos[ch].append(loc+1) lociPos[ch].append(loc+1 + DSLdist[j]) j += 1 else: loci[ch] += 1 lociPos[ch].append(loc+1) i += 1 # non-DSL loci, for convenience nonDSL = range(0, reduce(operator.add, loci)) for loc in DSL: nonDSL.remove(loc) ### ### initialization ### if maxAle > 1: # Not SNP preOperators = [ # initialize all loci with 5 haplotypes initByValue(value=[[x]*sum(loci) for x in range(48, 53)], proportions=[.2]*5), # and then init DSL with all wild type alleles initByValue([0]*len(DSL), atLoci=DSL) ] else: # SNP preOperators = [ # initialize all loci with two haplotypes (0001,111) initByValue(value=[[x]*sum(loci) for x in [0,1] ], proportions=[.5]*2), # and then init DSL with all wild type alleles initByValue([0]*len(DSL), atLoci=DSL) ] ### ### mutation, start from gen 0, ### if maxAle > 1: # Not SNP # symmetric mutation model for microsatellite mutator = smmMutator(rate=mutaRate, maxAllele=maxAle, atLoci=nonDSL) else: # k-allele model for mutation of SNP mutator = kamMutator(rate=mutaRate, maxAllele=1, atLoci=nonDSL) ### ### Recombination ### if len(recRate) == 1: rec = recombinator(intensity=recRate[0]) else: # rec after ... if len(recRate) != sum(loci) - numChrom: raise exceptions.ValueError("Recombination rate specification is wrong. Please see help file") al = [] start = 0 for ch in range(numChrom): al.extend( [x+start for x in range(loci(ch) )] ) start += loci[ch] rec = recombinator(rate=recRate, afterLoci=al) ### ### output progress ### operators = [ mutator, rec, stat(alleleFreq=DSL, popSize=True, LD=[DSL[0], DSL[0]+1], step=1), # output to screen pyEval( expr=r'"%d(%d): "%(gen, popSize) + " ".join(["%.5f"%(1-alleleFreq[x][0]) for x in DSL])+" %f\n"%LD_prime[DSL[0]][DSL[0]+1]', step=100), # output to file (append) pyEval( expr=r'"%d %d " %(gen, popSize) + " ".join(["%.5f"%(1-alleleFreq[x][0]) for x in DSL])+"\n"', output='>>>'+filename+'.traj') ] ### ### introduction of disease mutants ### ### endingGen ### 0 1 ...... i_T for i in range(numDSL): operators.append( pointMutator(atLoci=[DSL[i]], toAllele=1, inds=[i], at = [introGens[i]], stage=PreMating ) ) ### ### split to subpopulations ### if numSubPop > 1: operators.append( splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[splitGen]), ) ### ### selection ### if mlSelModelTmp in ['additive', 'multiplicative']: mlSelModel = {'additive':SEL_Additive, 'multiplicative':SEL_Multiplicative}[mlSelModelTmp] operators.append( mlSelector( # with five multiple-allele selector as parameter [ maSelector(locus=DSL[x], wildtype=[0], fitness=[fitness[3*x],fitness[3*x+1],fitness[3*x+2]]) for x in range(len(DSL)) ], mode=mlSelModel, begin=splitGen), ) elif mlSelModelTmp == 'interaction': # multi-allele selector can handle multiple DSL case operators.append( maSelector(loci=DSL, fitness=fitness, wildtype=[0]) ) ### ### migration ### if numSubPop > 1 and migrModel == 'island' and migrRate > 0: operators.append( migrator(migrIslandRates(migrRate, numSubPop), mode=MigrByProbability, begin=mixingGen) ) elif numSubPop > 1 and migrModel == 'stepping stone' and migrRate > 0: operators.append( migrator(migrSteppingStoneRates(migrRate, numSubPop, circular=True), mode=MigrByProbability, begin=mixingGen) ) ### ### output statistics, track performance ### operators.extend([ pyOperator(func=outputStatistics, param = (burninGen, splitGen, mixingGen, endingGen, filename+'.log'), at = [burninGen, splitGen, mixingGen, endingGen ] ), # show elapsed time ticToc(at=[burninGen, splitGen, mixingGen, endingGen]), ] ) if len(savePop) > 0: # save population at given generations operators.append(savePopulation(outputExpr='os.path.join(simuName, "%s_%d.%s" % (simuName, gen, format))', at=savePop)) ### ### prepare mating scheme ### ### use ancestralDepth, def saveAncestors(gen): if gen >= endingGen - savedGen: return savedGen else: return 1 # create a population, note that I add needed information # fields father_idx, mother_idx later on, with the hope # that simulation can run a bit faster without them. pop = population(subPop=popSizeFunc(0), ploidy=2, loci = loci, maxAllele = maxAle, lociPos = lociPos, infoFields = ['fitness']) # save DSL info, some operators will use it. pop.dvars().DSL = DSL pop.dvars().numLoci = numLoci pop.dvars().curAlleleFreq = curAlleleFreq # clear log file if it exists try: os.remove(filename+'.log') except: pass # # start simulation. simu = simulator( pop, controlledRandomMating( newSubPopSizeFunc=popSizeFunc, # demographic model loci=DSL, # which loci to control alleles=[1]*numDSL, # which allele to control freqFunc=trajFunc # frequency control function ), rep=1) # evolve! If --dryrun is set, only show info simu.evolve( preOps = preOperators, ops = operators, end=endingGen-savedGen, dryrun=dryrun ) if dryrun: raise exceptions.SystemError("Stop since in dryrun mode.") # prepare for the last several generations # change mating scheme to random mating. # # save saveGen-1 ancestral generations simu.population(0).setAncestralDepth(savedGen-1) simu.population(0).addInfoFields(['father_idx', 'mother_idx']) operators.append(parentsTagger()) simu.setMatingScheme( randomMating( newSubPopSizeFunc=popSizeFunc, # demographic model numOffspring = numOffspring, mode = {'constant': MATE_NumOffspring, 'geometric': MATE_GeometricDistribution }[numOffMode] ) ) # different evolution method for the last few generations simu.evolve(ops=operators, end=endingGen) # succeed save information pop = simu.population(0) # we want to save info on how this population is generated. # This is not required but is a good practise pop.dvars().DSLafter = DSLafter pop.dvars().DSLdist = DSLdist pop.dvars().initSize = initSize pop.dvars().endingSize = endingSize pop.dvars().burninGen = burninGen pop.dvars().splitGen = splitGen pop.dvars().mixingGen = mixingGen pop.dvars().endingGen = endingGen pop.dvars().numSubPop = numSubPop pop.dvars().mutaRate = mutaRate pop.dvars().mutaModel = "symmetric stepwise" 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' #TurnOnDebug(DBG_UTILITY) simu.population(0).savePopulation(filename+'.'+format) return True
|
introFree, selFreeIntensity, initSize, endingSize, growthModel,
|
initSize, endingSize, growthModel,
|
def saveAncestors(gen): if gen >= endingGen - savedGen: return savedGen else: return 1
|
options['command'] = 'qsub'
|
def readConfigFile(): ''' read variables from configuration file ''' config = os.path.join(os.environ['HOME'], '.simuCluster') tmp = {} res = {} if os.path.isfile(config): execfile(config, tmp, res) return res
|
|
assert (simu.dvars(0).haploFreq['0-1']['2-3'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['3-4'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['4-5'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['5-6'] - 0.05) < 0.01
|
assert (simu.dvars(0).haploFreq['2-3']['1-2'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['3-4']['1-2'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['4-5']['1-2'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['5-6']['1-2'] - 0.05) < 0.01 def testRecRates(self): ' see if we actually recombine at this rate ' pop = population(10000, loci=[2,3,2]) InitByValue(pop, value=[1]*7+[2]*7) simu = simulator(pop, randomMating()) simu.step( [ stat( haploFreq = [[0,1], [2,3], [3,4], [4,5], [5,6]]), recombinator(rate = [0.1,0.15,0.2,0.3], afterLoci=[0,2,3,5] ) ] ) assert (simu.dvars(0).haploFreq['0-1']['1-2'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['2-3']['1-2'] - 0.075)< 0.01 assert (simu.dvars(0).haploFreq['3-4']['1-2'] - 0.1) < 0.01 assert (simu.dvars(0).haploFreq['4-5']['1-2'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['5-6']['1-2'] - 0.15) < 0.01 def testRecIntensity(self): ' see if we actually recombine at this rate ' pop = population(10000, loci=[2,3,2], lociDist=[0,1,0,2,4,0,4] ) InitByValue(pop, value=[1]*7+[2]*7) simu = simulator(pop, randomMating()) simu.step( [ stat( haploFreq = [[0,1], [2,3], [3,4], [4,5], [5,6]]), recombinator(intensity = 0.1) ] ) assert (simu.dvars(0).haploFreq['0-1']['1-2'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['2-3']['1-2'] - 0.1) < 0.01 assert (simu.dvars(0).haploFreq['3-4']['1-2'] - 0.1) < 0.01 assert (simu.dvars(0).haploFreq['4-5']['1-2'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['5-6']['1-2'] - 0.2) < 0.01 def testRecIntensityAfterLoci(self): ' see if we actually recombine at this rate ' pop = population(10000, loci=[2,3,2], lociDist=[0,1,0,2,4,0,4] ) InitByValue(pop, value=[1]*7+[2]*7) simu = simulator(pop, randomMating()) simu.step( [ stat( haploFreq = [[0,1], [2,3], [3,4], [4,5], [5,6]]), recombinator(intensity = 0.1, afterLoci=[2,5]) ] ) assert simu.dvars(0).haploFreq['0-1'].setdefault('1-2',0) == 0 assert (simu.dvars(0).haploFreq['2-3']['1-2'] - 0.1) < 0.01 assert simu.dvars(0).haploFreq['3-4'].setdefault('1-2',0) == 0 assert (simu.dvars(0).haploFreq['4-5']['1-2'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['5-6']['1-2'] - 0.2) < 0.01
|
def testRecRate(self): ' see if we actually recombine at this rate ' pop = population(10000, loci=[2,3,2]) InitByValue(pop, value=[1]*7+[2]*7) simu = simulator(pop, randomMating()) simu.step( [ stat( haploFreq = [[0,1], [2,3], [3,4], [4,5], [5,6]]), recombinator(rate = 0.1) ] ) # the supposed proportions are 1-1: 0.5-r/2, 1-2: r/2, 2-1: r/2, 2-2: 0.5-r/2 assert (simu.dvars(0).haploFreq['0-1']['1-2'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['2-3'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['3-4'] - 0.05) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['4-5'] - 0.25) < 0.01 assert (simu.dvars(0).haploFreq['0-1']['5-6'] - 0.05) < 0.01
|
def testRecombine(self):
|
def testRecProportion(self):
|
def testRecombine(self): ' verify table 4 of H&C 3nd edition P49 ' N = 10000 r = 0.1 genoDad = [[1,1],[1,1],[1,1],[1,1],[1,2],[1,2],[1,2],[2,1],[2,1],[2,2]] genoMom = [[1,1],[1,2],[2,1],[2,2],[1,2],[2,1],[2,2],[2,1],[2,2],[2,2]] prop = [ [1, 0, 0, 0], [.5, .5, 0, 0], [.5, 0, 0.5, 0], [0.5-r/2, r/2, r/2, 0.5-r/2], [0, 1, 0, 0], [r/2, .5-r/2, .5-r/2, r/2], [0, .5, 0, .5], [0, 0, 1, 0], [0, 0, .5, .5], [0, 0, 0, 1] ] for i in range(0, len(genoDad)): pop = population(size=N, loci=[2]) InitByValue(pop, value=genoDad[i]+genoMom[i]) simu = simulator(pop, randomMating()) simu.step( [ recombinator(rate=r), stat(haploFreq=[0,1]) ]) hf = simu.dvars(0).haploFreq['0-1'] assert not ((hf.setdefault('1-1',0) - prop[i][0]) > 0.01 or \ (hf.setdefault('1-2',0) - prop[i][1]) > 0.01 or \ (hf.setdefault('2-1',0) - prop[i][2]) > 0.01 or \ (hf.setdefault('2-2',0) - prop[i][3]) > 0.01), \ "Recombination results in potentially wrong proportions." + \ str( genoDad[i]) + ' crossing ' + str(genoMom[i])
|
pass
|
r = 0.1 N = 100 pop = population(size=N, loci=[2,5], sexChrom=True) InitByValue(pop, indRange=[0,N/2-1], sex=[Male]*(N/2), atPloidy=0, value=[1]*7) InitByValue(pop, indRange=[0,N/2-1], sex=[Male]*(N/2), atPloidy=1, value=[3]*7) InitByValue(pop, indRange=[N/2,N-1], sex=[Female]*(N/2), value=[1]*7+[2]*7) simu = simulator(pop, randomMating()) simu.evolve( [ recombinator(rate=r) ], end=100) pop = simu.population(0) for i in range( pop.popSize() ): ind = pop.individual(i) if ind.sex() == Male: assert ind.arrGenotype(1, 1) == carray('B', [3]*5) else: assert ind.arrGenotype().count(3) == 0
|
def testNoMaleRec(self): ' male chromosome is not supposed to recombine ' # create such an situation
|
selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[1] )
|
selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[0] )
|
def simuCDCV( numDSL, initSpec, selModel, selModelAllDSL, selCoef, mutaModel, maxAllele, mutaRate, initSize, finalSize, burnin, noMigrGen, mixingGen, growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop, resume, resumeAtGen, name, dryrun): ''' parameters are self-expanary. See help info for detailed simulation scheme. ''' # generations mixing = burnin + noMigrGen end = mixing + mixingGen # pop size if growth == 'linear': incFunc = LinearExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'exponential': incFunc = ExponentialExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'instant': incFunc = InstantExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) # # create a simulator, if not in resume mode if resume == '': simu = simulator( population(subPop=incFunc(0), loci=[1]*(numDSL), maxAllele = maxAllele, infoFields=['fitness']), randomMating(newSubPopSizeFunc=incFunc) ) else: try: print "Resuming simulation from file ", resume, " at generation ", resumeAtGen pop = LoadPopulation(resume) simu = simulator(pop, randomMating(newSubPopSizeFunc=incFunc)) simu.setGen(resumeAtGen) except exceptions.Exception, e: print "Can not resume from population "+ resume + ". Aborting." raise e # determine mutation etc if mutaModel == 'k-allele': mutation = kamMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) else: mutation = smmMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) # determine selection # if selModelAllDSL == 'customized': selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[1] ) else: sel = [] for d in range(numDSL): if selModel[d] == 'recessive': sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[1])) else: sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[1])) # now, the whole selector if selModelAllDSL == 'additive': selection = mlSelector( sel, mode=SEL_Additive) elif selModelAllDSL == 'multiplicative': selection = mlSelector( sel, mode=SEL_Multiplicative) # migration if numSubPop == 1 or migrModel == 'none': # no migration migration = noneOp() else: if migrModel == 'island': migration = migrator(migrIslandRates(migrRate, numSubPop), begin=mixing) else: migration = migrator(migrStepstoneRates(migrRate, numSubPop, circular=True), begin=mixing) # # prepare log file, if not in resume mode if resume == '': # not resume logOutput = open(os.path.join(name, name+'.log'), 'w') logOutput.write("gen\t") for d in range(numDSL): logOutput.write( 'ne\tn\tf0\tp1\tp5\tanc\t') logOutput.write("\n") logOutput.close() # use global global allelesBeforeExpansion allelesBeforeExpansion = [] global NeHist, NeMax, FHist, FMax # determine plot label plotLabel = [] for i in range(numDSL): if selModelAllDSL == 'customized': plotLabel.append('mu=%g, s=customized' % mutaRate[i]) else: plotLabel.append('mu=%g, s=%g' % (mutaRate[i], selCoef[i])) # history of Ne, the first one is gen NeHist = [] FHist = [] for i in range(numDSL+1): NeHist.append( [] ) FHist.append( [] ) NeMax = 0 FMax = 0 # start evolution simu.evolve( # start evolution preOps= # initialize DSL [initByFreq(atLoci=[x], alleleFreq=initSpec[x]) for x in range(numDSL)], ops=[ # report population size, for monitoring purpose only # count allele frequencies at both loci stat(popSize=True, alleleFreq=range(numDSL)), # report generation and popsize pyEval(r"'%d\t%d\n' % (gen, popSize)", step=50), # # record alleles before expansion, used to count percentage of alleles derived # from before expansion. pyExec('global allelesBeforeExpansion\n'+ '''for i in range(%d): allelesBeforeExpansion.append([]) for a in range(2,len(alleleNum[i])): if alleleNum[i][a] != 0: allelesBeforeExpansion[i].append(a) print "Ancestral alleles before expansion: ", allelesBeforeExpansion[i]''' % \ (numDSL), at=[burnin]), # splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[burnin]), # mutate mutation, # selection selection, # migration migration, # visualizer pyOperator(func=PlotSpectra, param=(numDSL, saveAt, 50, dispPlot, plotLabel, name), step=update ), # pause when needed #pause(stopOnKeyStroke=True), # monitor execution time ticToc(step=100), ## pause at any user key input (for presentation purpose) ## pause(stopOnKeyStroke=1) ], end=end, dryrun = dryrun ) # if savePop != '': simu.population(0).savePopulation(savePop)
|
sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[1]))
|
sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[0]))
|
def simuCDCV( numDSL, initSpec, selModel, selModelAllDSL, selCoef, mutaModel, maxAllele, mutaRate, initSize, finalSize, burnin, noMigrGen, mixingGen, growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop, resume, resumeAtGen, name, dryrun): ''' parameters are self-expanary. See help info for detailed simulation scheme. ''' # generations mixing = burnin + noMigrGen end = mixing + mixingGen # pop size if growth == 'linear': incFunc = LinearExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'exponential': incFunc = ExponentialExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'instant': incFunc = InstantExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) # # create a simulator, if not in resume mode if resume == '': simu = simulator( population(subPop=incFunc(0), loci=[1]*(numDSL), maxAllele = maxAllele, infoFields=['fitness']), randomMating(newSubPopSizeFunc=incFunc) ) else: try: print "Resuming simulation from file ", resume, " at generation ", resumeAtGen pop = LoadPopulation(resume) simu = simulator(pop, randomMating(newSubPopSizeFunc=incFunc)) simu.setGen(resumeAtGen) except exceptions.Exception, e: print "Can not resume from population "+ resume + ". Aborting." raise e # determine mutation etc if mutaModel == 'k-allele': mutation = kamMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) else: mutation = smmMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) # determine selection # if selModelAllDSL == 'customized': selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[1] ) else: sel = [] for d in range(numDSL): if selModel[d] == 'recessive': sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[1])) else: sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[1])) # now, the whole selector if selModelAllDSL == 'additive': selection = mlSelector( sel, mode=SEL_Additive) elif selModelAllDSL == 'multiplicative': selection = mlSelector( sel, mode=SEL_Multiplicative) # migration if numSubPop == 1 or migrModel == 'none': # no migration migration = noneOp() else: if migrModel == 'island': migration = migrator(migrIslandRates(migrRate, numSubPop), begin=mixing) else: migration = migrator(migrStepstoneRates(migrRate, numSubPop, circular=True), begin=mixing) # # prepare log file, if not in resume mode if resume == '': # not resume logOutput = open(os.path.join(name, name+'.log'), 'w') logOutput.write("gen\t") for d in range(numDSL): logOutput.write( 'ne\tn\tf0\tp1\tp5\tanc\t') logOutput.write("\n") logOutput.close() # use global global allelesBeforeExpansion allelesBeforeExpansion = [] global NeHist, NeMax, FHist, FMax # determine plot label plotLabel = [] for i in range(numDSL): if selModelAllDSL == 'customized': plotLabel.append('mu=%g, s=customized' % mutaRate[i]) else: plotLabel.append('mu=%g, s=%g' % (mutaRate[i], selCoef[i])) # history of Ne, the first one is gen NeHist = [] FHist = [] for i in range(numDSL+1): NeHist.append( [] ) FHist.append( [] ) NeMax = 0 FMax = 0 # start evolution simu.evolve( # start evolution preOps= # initialize DSL [initByFreq(atLoci=[x], alleleFreq=initSpec[x]) for x in range(numDSL)], ops=[ # report population size, for monitoring purpose only # count allele frequencies at both loci stat(popSize=True, alleleFreq=range(numDSL)), # report generation and popsize pyEval(r"'%d\t%d\n' % (gen, popSize)", step=50), # # record alleles before expansion, used to count percentage of alleles derived # from before expansion. pyExec('global allelesBeforeExpansion\n'+ '''for i in range(%d): allelesBeforeExpansion.append([]) for a in range(2,len(alleleNum[i])): if alleleNum[i][a] != 0: allelesBeforeExpansion[i].append(a) print "Ancestral alleles before expansion: ", allelesBeforeExpansion[i]''' % \ (numDSL), at=[burnin]), # splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[burnin]), # mutate mutation, # selection selection, # migration migration, # visualizer pyOperator(func=PlotSpectra, param=(numDSL, saveAt, 50, dispPlot, plotLabel, name), step=update ), # pause when needed #pause(stopOnKeyStroke=True), # monitor execution time ticToc(step=100), ## pause at any user key input (for presentation purpose) ## pause(stopOnKeyStroke=1) ], end=end, dryrun = dryrun ) # if savePop != '': simu.population(0).savePopulation(savePop)
|
sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[1]))
|
sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[0]))
|
def simuCDCV( numDSL, initSpec, selModel, selModelAllDSL, selCoef, mutaModel, maxAllele, mutaRate, initSize, finalSize, burnin, noMigrGen, mixingGen, growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop, resume, resumeAtGen, name, dryrun): ''' parameters are self-expanary. See help info for detailed simulation scheme. ''' # generations mixing = burnin + noMigrGen end = mixing + mixingGen # pop size if growth == 'linear': incFunc = LinearExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'exponential': incFunc = ExponentialExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'instant': incFunc = InstantExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) # # create a simulator, if not in resume mode if resume == '': simu = simulator( population(subPop=incFunc(0), loci=[1]*(numDSL), maxAllele = maxAllele, infoFields=['fitness']), randomMating(newSubPopSizeFunc=incFunc) ) else: try: print "Resuming simulation from file ", resume, " at generation ", resumeAtGen pop = LoadPopulation(resume) simu = simulator(pop, randomMating(newSubPopSizeFunc=incFunc)) simu.setGen(resumeAtGen) except exceptions.Exception, e: print "Can not resume from population "+ resume + ". Aborting." raise e # determine mutation etc if mutaModel == 'k-allele': mutation = kamMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) else: mutation = smmMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) # determine selection # if selModelAllDSL == 'customized': selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[1] ) else: sel = [] for d in range(numDSL): if selModel[d] == 'recessive': sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[1])) else: sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[1])) # now, the whole selector if selModelAllDSL == 'additive': selection = mlSelector( sel, mode=SEL_Additive) elif selModelAllDSL == 'multiplicative': selection = mlSelector( sel, mode=SEL_Multiplicative) # migration if numSubPop == 1 or migrModel == 'none': # no migration migration = noneOp() else: if migrModel == 'island': migration = migrator(migrIslandRates(migrRate, numSubPop), begin=mixing) else: migration = migrator(migrStepstoneRates(migrRate, numSubPop, circular=True), begin=mixing) # # prepare log file, if not in resume mode if resume == '': # not resume logOutput = open(os.path.join(name, name+'.log'), 'w') logOutput.write("gen\t") for d in range(numDSL): logOutput.write( 'ne\tn\tf0\tp1\tp5\tanc\t') logOutput.write("\n") logOutput.close() # use global global allelesBeforeExpansion allelesBeforeExpansion = [] global NeHist, NeMax, FHist, FMax # determine plot label plotLabel = [] for i in range(numDSL): if selModelAllDSL == 'customized': plotLabel.append('mu=%g, s=customized' % mutaRate[i]) else: plotLabel.append('mu=%g, s=%g' % (mutaRate[i], selCoef[i])) # history of Ne, the first one is gen NeHist = [] FHist = [] for i in range(numDSL+1): NeHist.append( [] ) FHist.append( [] ) NeMax = 0 FMax = 0 # start evolution simu.evolve( # start evolution preOps= # initialize DSL [initByFreq(atLoci=[x], alleleFreq=initSpec[x]) for x in range(numDSL)], ops=[ # report population size, for monitoring purpose only # count allele frequencies at both loci stat(popSize=True, alleleFreq=range(numDSL)), # report generation and popsize pyEval(r"'%d\t%d\n' % (gen, popSize)", step=50), # # record alleles before expansion, used to count percentage of alleles derived # from before expansion. pyExec('global allelesBeforeExpansion\n'+ '''for i in range(%d): allelesBeforeExpansion.append([]) for a in range(2,len(alleleNum[i])): if alleleNum[i][a] != 0: allelesBeforeExpansion[i].append(a) print "Ancestral alleles before expansion: ", allelesBeforeExpansion[i]''' % \ (numDSL), at=[burnin]), # splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[burnin]), # mutate mutation, # selection selection, # migration migration, # visualizer pyOperator(func=PlotSpectra, param=(numDSL, saveAt, 50, dispPlot, plotLabel, name), step=update ), # pause when needed #pause(stopOnKeyStroke=True), # monitor execution time ticToc(step=100), ## pause at any user key input (for presentation purpose) ## pause(stopOnKeyStroke=1) ], end=end, dryrun = dryrun ) # if savePop != '': simu.population(0).savePopulation(savePop)
|
pyEval(r"'%d\t%d\n' % (gen, popSize)", step=50),
|
pyEval(r"'%d\t%d\t%f\n' % (gen, popSize, alleleFreq[0][0])", step=50),
|
def simuCDCV( numDSL, initSpec, selModel, selModelAllDSL, selCoef, mutaModel, maxAllele, mutaRate, initSize, finalSize, burnin, noMigrGen, mixingGen, growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop, resume, resumeAtGen, name, dryrun): ''' parameters are self-expanary. See help info for detailed simulation scheme. ''' # generations mixing = burnin + noMigrGen end = mixing + mixingGen # pop size if growth == 'linear': incFunc = LinearExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'exponential': incFunc = ExponentialExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'instant': incFunc = InstantExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) # # create a simulator, if not in resume mode if resume == '': simu = simulator( population(subPop=incFunc(0), loci=[1]*(numDSL), maxAllele = maxAllele, infoFields=['fitness']), randomMating(newSubPopSizeFunc=incFunc) ) else: try: print "Resuming simulation from file ", resume, " at generation ", resumeAtGen pop = LoadPopulation(resume) simu = simulator(pop, randomMating(newSubPopSizeFunc=incFunc)) simu.setGen(resumeAtGen) except exceptions.Exception, e: print "Can not resume from population "+ resume + ". Aborting." raise e # determine mutation etc if mutaModel == 'k-allele': mutation = kamMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) else: mutation = smmMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) # determine selection # if selModelAllDSL == 'customized': selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[1] ) else: sel = [] for d in range(numDSL): if selModel[d] == 'recessive': sel.append( maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[1])) else: sel.append( maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[1])) # now, the whole selector if selModelAllDSL == 'additive': selection = mlSelector( sel, mode=SEL_Additive) elif selModelAllDSL == 'multiplicative': selection = mlSelector( sel, mode=SEL_Multiplicative) # migration if numSubPop == 1 or migrModel == 'none': # no migration migration = noneOp() else: if migrModel == 'island': migration = migrator(migrIslandRates(migrRate, numSubPop), begin=mixing) else: migration = migrator(migrStepstoneRates(migrRate, numSubPop, circular=True), begin=mixing) # # prepare log file, if not in resume mode if resume == '': # not resume logOutput = open(os.path.join(name, name+'.log'), 'w') logOutput.write("gen\t") for d in range(numDSL): logOutput.write( 'ne\tn\tf0\tp1\tp5\tanc\t') logOutput.write("\n") logOutput.close() # use global global allelesBeforeExpansion allelesBeforeExpansion = [] global NeHist, NeMax, FHist, FMax # determine plot label plotLabel = [] for i in range(numDSL): if selModelAllDSL == 'customized': plotLabel.append('mu=%g, s=customized' % mutaRate[i]) else: plotLabel.append('mu=%g, s=%g' % (mutaRate[i], selCoef[i])) # history of Ne, the first one is gen NeHist = [] FHist = [] for i in range(numDSL+1): NeHist.append( [] ) FHist.append( [] ) NeMax = 0 FMax = 0 # start evolution simu.evolve( # start evolution preOps= # initialize DSL [initByFreq(atLoci=[x], alleleFreq=initSpec[x]) for x in range(numDSL)], ops=[ # report population size, for monitoring purpose only # count allele frequencies at both loci stat(popSize=True, alleleFreq=range(numDSL)), # report generation and popsize pyEval(r"'%d\t%d\n' % (gen, popSize)", step=50), # # record alleles before expansion, used to count percentage of alleles derived # from before expansion. pyExec('global allelesBeforeExpansion\n'+ '''for i in range(%d): allelesBeforeExpansion.append([]) for a in range(2,len(alleleNum[i])): if alleleNum[i][a] != 0: allelesBeforeExpansion[i].append(a) print "Ancestral alleles before expansion: ", allelesBeforeExpansion[i]''' % \ (numDSL), at=[burnin]), # splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[burnin]), # mutate mutation, # selection selection, # migration migration, # visualizer pyOperator(func=PlotSpectra, param=(numDSL, saveAt, 50, dispPlot, plotLabel, name), step=update ), # pause when needed #pause(stopOnKeyStroke=True), # monitor execution time ticToc(step=100), ## pause at any user key input (for presentation purpose) ## pause(stopOnKeyStroke=1) ], end=end, dryrun = dryrun ) # if savePop != '': simu.population(0).savePopulation(savePop)
|
if j not in proc_jobs and n in all_jobs:
|
if j not in proc_jobs and j in all_jobs:
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
def testBinormialSelection(self):
|
def testBinomialSelection(self):
|
def testBinormialSelection(self): 'Testing binomialSelection mating scheme (FIXME: imcomplete)' simu = simulator(population(10, loci=[1], ploidy=1), binomialSelection())
|
return with_mode(NO_CONVERSION, r.do_call)('rbind', mat)
|
return r.do_call('rbind', mat)
|
def rmatrix(mat): ''' VERY IMPORTANT convert a Python 2d list to r matrix format that can be passed to functions like image directly. ''' return with_mode(NO_CONVERSION, r.do_call)('rbind', mat)
|
self.mfrow = mfrow
|
self.mfrow = [int(x) for x in mfrow]
|
def __init__(self, nplot, update, title, xlab, ylab, axes, lty, col, mfrow, plotType, saveAs, leaveOpen, dev='', width=0, height=0): """ initialization function of base properties (layout etc) of all plotters """ # save parameters self.nplot = nplot self.axes = axes if lty==[]: self.lty = range(1, nplot+1) else: self.lty = lty if col==[]: self.col = [0]*nplot else: self.col = col self.mfrow = mfrow self.update = update self.title = [title]*self.nplot self.xlab = xlab self.ylab = ylab self.plotType = plotType self.saveAs = saveAs self.leaveOpen = leaveOpen self.width = width self.height = height # layout related variables self.first = True # R plot device number self.dev = dev self.device = 1 # update related variable self.skip = -1
|
self.mfrow[0] = int(math.ceil(math.sqrt( self.nplot ))) self.mfrow[1] = int(math.ceil(self.nplot/float(self.mfrow[0]) ))
|
self.mfrow[0] = int(ceil(sqrt( self.nplot))) self.mfrow[1] = int(ceil(self.nplot/float(self.mfrow[0])))
|
def layout(self): # calculate layout if self.mfrow != [1,1] and self.mfrow[0]*self.mfrow[1] < self.nplot: raise ValueError("mfrow is not enough to hold " + str(self.nplot) + " figures")
|
w = 7 * r.par("csi") * 2.54
|
w = 7 * with_mode(BASIC_CONVERSION, r.par)("csi") * 2.54
|
def layout(self): # calculate layout if self.mfrow != [1,1] and self.mfrow[0]*self.mfrow[1] < self.nplot: raise ValueError("mfrow is not enough to hold " + str(self.nplot) + " figures")
|
levels = r.seq(lim[0], lim[1], length=level)
|
levels = with_mode(BASIC_CONVERSION, r.seq)(lim[0], lim[1], length=level)
|
def colorBar(self, level, lim): " draw a color bar to the right of the plot" mar = [0]*4 mar[0] = [5, 1, 4, 2] self.color = r.rainbow(level, start=.7, end=.1) r.par(mar=mar) levels = r.seq(lim[0], lim[1], length=level) r.plot_new() r.plot_window(xlim = [0, 1], ylim = lim, xaxs = "i", yaxs = "i") r.rect(0, levels[:(len(levels)-1)], 1, levels[1:], col = self.color) r.axis(4) r.box() mar[3] = 1 r.par(mar = mar)
|
xlim=self.xlim, z= r.t(r.matrix( self.data[rep].flatData(),axes=self.axes, byrow=True, ncol=len(self.data[rep].data[0]))),xlab=self.xlab,
|
xlim=self.xlim, z= r.t(r.matrix(self.data[rep].flatData(), byrow=True, ncol=len(self.data[rep].data[0]))), xlab=self.xlab, axes=self.axes,
|
def plot(self, pop, expr): gen = pop.gen() rep = pop.rep() data = pop.evaluate(expr) _data = data # now start! if type(_data) == type(0) or type(_data) == type(0.): _data = [_data]
|
def getScript(name):
|
def getScript(name, options):
|
def getScript(name): ''' return the script for simulation 'name' ''' if not globals().has_key('script'): print 'Vairable script is not defined' sys.exit(0) # for job in alljobs: # a dictionary if job['name'] == name: s = script print alljobs, job for k,v in job.items(): # subsitute in script if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) for k, v in options.items(): if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) return s
|
print alljobs, job for k,v in job.items():
|
for k,v in (job.items() + options.items()):
|
def getScript(name): ''' return the script for simulation 'name' ''' if not globals().has_key('script'): print 'Vairable script is not defined' sys.exit(0) # for job in alljobs: # a dictionary if job['name'] == name: s = script print alljobs, job for k,v in job.items(): # subsitute in script if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) for k, v in options.items(): if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) return s
|
if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s)
|
if True in [x in str(v) for x in [' ', '*', ',', '[', ']']]: if '"' in str(v): quote = '"' else: quote = "'" s = re.sub(r'\$%s(\W)' % k, r"%s%s%s\1" % (quote, str(v), quote), s) s = re.sub(r'\$\{%s\}' % k, "%s%s%s" % (quote, str(v), quote), s)
|
def getScript(name): ''' return the script for simulation 'name' ''' if not globals().has_key('script'): print 'Vairable script is not defined' sys.exit(0) # for job in alljobs: # a dictionary if job['name'] == name: s = script print alljobs, job for k,v in job.items(): # subsitute in script if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) for k, v in options.items(): if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) return s
|
s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) for k, v in options.items(): if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s)
|
s = re.sub(r'\$%s(\W)' % k, r"%s\1" % str(v), s) s = re.sub(r'\$\{%s\}' % k, str(v), s)
|
def getScript(name): ''' return the script for simulation 'name' ''' if not globals().has_key('script'): print 'Vairable script is not defined' sys.exit(0) # for job in alljobs: # a dictionary if job['name'] == name: s = script print alljobs, job for k,v in job.items(): # subsitute in script if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) for k, v in options.items(): if '"' in 'v': s = re.sub(r'\$%s\s' % k, "'%s' " % v, s) s = re.sub(r'\$\{%s\}' % k, "'%s' " % v, s) else: s = re.sub(r'\$%s\s' % k, '"%s" ' % v, s) s = re.sub(r'\$\{%s\}' % k, '"%s" ' % v, s) return s
|
options = {}
|
options = {'time':96}
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print alljobs
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
|
print getScript(proc_jobs[0])
|
print getScript(proc_jobs[0], options)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
print >> pbs, getScript(job)
|
print >> pbs, getScript(job, options)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
os.system('qsub ' + job + '.pbs')
|
print "Submitting job via 'qsub %s.pbs'" % job os.system('qsub %s.pbs' % job)
|
def allJobs(): ''' list all jobs ''' names = [] for job in alljobs: names.append(job['name']) return names
|
'simuUtil', 'simuSciPy', 'simuMatPlt', 'simuRPy', 'simuViewPop' ],
|
'simuPOP_ba', 'simuPOP_baop', 'simuUtil', 'simuSciPy', 'simuMatPlt', 'simuRPy', 'simuViewPop' ],
|
def buildStaticLibrary(sourceFiles, libName, libDir, compiler): '''Build libraries to be linked to simuPOP modules''' # get a c compiler print 'Creating library', libName comp = new_compiler(compiler=compiler, verbose=True) objFiles = comp.compile(sourceFiles, include_dirs=['.']) comp.create_static_lib(objFiles, libName, libDir)
|
self.assertUnqqual([x.allele(0,0) for x in pop.individuals(0)], [int(x) for x in pop.indInfo('a', 0, False)])
|
def testRearrange(self): 'Test if info and genotype are migrated with individuals' if alleleType() == 'binary': return #TurnOnDebug(DBG_POPULATION) pop = population(subPop=[4, 6], loci=[1], infoFields=['a','b']) pop.arrGenotype(True)[:] = range(20) pop.arrIndInfo(True)[:] = range(20) self.assertEqual([x.allele(0,0) for x in pop.individuals(0)], [int(x) for x in pop.indInfo('a', 0, True)]) self.assertEqual([x.allele(0,0) for x in pop.individuals(1)], [int(x) for x in pop.indInfo('a', 1, True)]) PyMigrate(pop, subPopID=[1,1,1,1,0,0,0,0,0,0]) # from ind, this should be fine. self.assertEqual([x.allele(0,0) for x in pop.individuals(0)], [x.info('a') for x in pop.individuals(0)]) self.assertEqual([x.allele(0,0) for x in pop.individuals(1)], [x.info('a') for x in pop.individuals(1)]) # Is info rearranged? self.assertUnqqual([x.allele(0,0) for x in pop.individuals(0)], [int(x) for x in pop.indInfo('a', 0, False)]) # if we force reorder self.assertEqual([x.allele(0,0) for x in pop.individuals(0)], [int(x) for x in pop.indInfo('a', 0, True)]) self.assertEqual([x.allele(0,0) for x in pop.individuals(1)], [int(x) for x in pop.indInfo('a', 1, True)])
|
|
self.assertEqual(simu.population(i), simu.population(i))
|
self.assertEqual(simu.population(i), simu1.population(i))
|
def testClone(self): 'Testing cloning of simulator' pop = population(subPop=[10,4], loci=[2,5]) simu = simulator(pop, randomMating(), rep = 3) simu.evolve( preOps = [initByFreq([0.3, .7])], ops = [stat(alleleFreq=range(pop.totNumLoci()))], end = 10 ) simu1 = simu.clone() for i in range(3): self.assertEqual(simu.population(i), simu.population(i))
|
define_macros = [ ('SIMUPOP_MODULE', '"simuPOP_std"')] + serial_macro,
|
define_macros = [ ('SIMUPOP_MODULE', 'simuPOP_std')] + serial_macro,
|
def addCarrayEntry(file): ' add a line at the wrap file for carray type definition' shutil.copy(file, file+'tmp') ofile = open(file, 'w') ifile = open(file+'tmp', 'r') for line in ifile.readlines(): if line.find('static PyMethodDef SwigMethods[] = ') != -1: ofile.write('''static PyMethodDef SwigMethods[] = { /* add carray entries */ { (char*)"carray", a_array, METH_VARARGS, a_array_doc}, ''') else: ofile.write(line) ifile.close() ofile.close() os.remove(file+'tmp')
|
define_macros = [ ('SIMUPOP_MODULE', '"simuPOP_op"'), ('OPTIMIZED', None)] + serial_macro,
|
define_macros = [ ('SIMUPOP_MODULE', 'simuPOP_op'), ('OPTIMIZED', None)] + serial_macro,
|
def addCarrayEntry(file): ' add a line at the wrap file for carray type definition' shutil.copy(file, file+'tmp') ofile = open(file, 'w') ifile = open(file+'tmp', 'r') for line in ifile.readlines(): if line.find('static PyMethodDef SwigMethods[] = ') != -1: ofile.write('''static PyMethodDef SwigMethods[] = { /* add carray entries */ { (char*)"carray", a_array, METH_VARARGS, a_array_doc}, ''') else: ofile.write(line) ifile.close() ofile.close() os.remove(file+'tmp')
|
define_macros = [ ('SIMUPOP_MODULE', '"simuPOP_la"'), ('LONGALLELE', None) ] + serial_macro,
|
define_macros = [ ('SIMUPOP_MODULE', 'simuPOP_la'), ('LONGALLELE', None) ] + serial_macro,
|
def addCarrayEntry(file): ' add a line at the wrap file for carray type definition' shutil.copy(file, file+'tmp') ofile = open(file, 'w') ifile = open(file+'tmp', 'r') for line in ifile.readlines(): if line.find('static PyMethodDef SwigMethods[] = ') != -1: ofile.write('''static PyMethodDef SwigMethods[] = { /* add carray entries */ { (char*)"carray", a_array, METH_VARARGS, a_array_doc}, ''') else: ofile.write(line) ifile.close() ofile.close() os.remove(file+'tmp')
|
define_macros = [ ('SIMUPOP_MODULE', '"simuPOP_laop"'), ('LONGALLELE', None), ('OPTIMIZED', None) ] + serial_macro,
|
define_macros = [ ('SIMUPOP_MODULE', 'simuPOP_laop'), ('LONGALLELE', None), ('OPTIMIZED', None) ] + serial_macro,
|
def addCarrayEntry(file): ' add a line at the wrap file for carray type definition' shutil.copy(file, file+'tmp') ofile = open(file, 'w') ifile = open(file+'tmp', 'r') for line in ifile.readlines(): if line.find('static PyMethodDef SwigMethods[] = ') != -1: ofile.write('''static PyMethodDef SwigMethods[] = { /* add carray entries */ { (char*)"carray", a_array, METH_VARARGS, a_array_doc}, ''') else: ofile.write(line) ifile.close() ofile.close() os.remove(file+'tmp')
|
for a in range(2,len(alleleNum[i])):
|
for a in range(1,len(alleleNum[i])):
|
def simuCDCV(numDSL, initSpec, selModel, selModelAllDSL, selCoef, mutaModel, maxAllele, mutaRate, initSize, finalSize, burnin, noMigrGen, mixingGen, growth, numSubPop, migrModel, migrRate, update, dispPlot, saveAt, savePop, resume, resumeAtGen, name, dryrun): ''' parameters are self-expanary. See help info for detailed simulation scheme. ''' # generations mixing = burnin + noMigrGen end = mixing + mixingGen # pop size if growth == 'linear': incFunc = LinearExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'exponential': incFunc = ExponentialExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) elif growth == 'instant': incFunc = InstantExpansion(initSize, finalSize, end, burnin, burnin, numSubPop) # # create a simulator, if not in resume mode if resume == '': simu = simulator( population(subPop=incFunc(0), loci=[1]*(numDSL), maxAllele = maxAllele, infoFields=['fitness']), randomMating(newSubPopSizeFunc=incFunc) ) else: try: print "Resuming simulation from file ", resume, " at generation ", resumeAtGen pop = LoadPopulation(resume) simu = simulator(pop, randomMating(newSubPopSizeFunc=incFunc)) simu.setGen(resumeAtGen) except exceptions.Exception, e: print "Can not resume from population "+ resume + ". Aborting." raise e # determine mutation etc if mutaModel == 'k-allele': mutation = kamMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) else: mutation = smmMutator(rate=mutaRate, atLoci=range(numDSL), maxAllele=maxAllele) # determine selection # if selModelAllDSL == 'customized': selection = maSelector( loci=range(numDSL), fitness=selCoef, wildtype=[0] ) else: sel = [] for d in range(numDSL): if selModel[d] == 'recessive': sel.append(maSelector(locus=d, fitness=[1,1,1-selCoef[d]], wildtype=[0])) else: sel.append(maSelector(locus=d, fitness=[1,1-selCoef[d]/2.,1-selCoef[d]], wildtype=[0])) # now, the whole selector if selModelAllDSL == 'additive': selection = mlSelector(sel, mode=SEL_Additive) elif selModelAllDSL == 'multiplicative': selection = mlSelector(sel, mode=SEL_Multiplicative) # migration if numSubPop == 1 or migrModel == 'none': # no migration migration = noneOp() else: if migrModel == 'island': migration = migrator(migrIslandRates(migrRate, numSubPop), begin=mixing) else: migration = migrator(migrStepstoneRates(migrRate, numSubPop, circular=True), begin=mixing) # # prepare log file, if not in resume mode if resume == '': # not resume logOutput = open(os.path.join(name, name+'.log'), 'w') logOutput.write("gen\t") for d in range(numDSL): logOutput.write( 'ne\tn\tf0\tp1\tp5\tanc\t') logOutput.write("\n") logOutput.close() # use global global allelesBeforeExpansion allelesBeforeExpansion = [] global NeHist, NeMax, FHist, FMax # determine plot label plotLabel = [] for i in range(numDSL): if selModelAllDSL == 'customized': plotLabel.append('mu=%g, s=customized' % mutaRate[i]) else: plotLabel.append('mu=%g, s=%g' % (mutaRate[i], selCoef[i])) # history of Ne, the first one is gen NeHist = [] FHist = [] for i in range(numDSL+1): NeHist.append( [] ) FHist.append( [] ) NeMax = 0 FMax = 0 # start evolution simu.evolve( # start evolution preOps= # initialize DSL [initByFreq(atLoci=[x], alleleFreq=initSpec[x]) for x in range(numDSL)], ops=[ # report population size, for monitoring purpose only # count allele frequencies at both loci stat(popSize=True, alleleFreq=range(numDSL), step=update), # report generation and popsize pyEval(r"'%d\t%d\t%f\n' % (gen, popSize, alleleFreq[0][0])", step=50), # # record alleles before expansion, used to count percentage of alleles derived # from before expansion. pyExec('global allelesBeforeExpansion\n'+ '''for i in range(%d): allelesBeforeExpansion.append([]) for a in range(2,len(alleleNum[i])): if alleleNum[i][a] != 0: allelesBeforeExpansion[i].append(a) print "Ancestral alleles before expansion: ", allelesBeforeExpansion[i]''' % \ (numDSL), at=[burnin]), # splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[burnin]), # mutate mutation, # selection selection, # migration migration, # visualizer pyOperator(func=PlotSpectra, param=(numDSL, saveAt, 50, dispPlot, plotLabel, name), step=update ), # monitor execution time ticToc(step=100), ## pause at any user key input (for presentation purpose) ## pause(stopOnKeyStroke=1) ], end=end, dryrun = dryrun ) # if savePop != '': simu.population(0).savePopulation(savePop)
|
ancNum += num[al-2]
|
ancNum += num[al-1]
|
def getStats(v, highest): # the following are statistics for each DSL perc = [] # percentage numAllele = [] # number of alleles effNumAllele = [] # effective number of alleles overallFreq = [] # size of disease percMostCommon = [] # percentage of most common perc5MostCommon = [] # percentage of five most common percAncestralAllele = [] # percentage of alleles from before expansion global allelesBeforeExpansion for d in range(numDSL): # overall DSA frequency overallFreq.append( 1 - v.alleleFreq[d][0]) if overallFreq[-1] == 0. : # no disease allele numAllele.append(0) effNumAllele.append(0) perc.append([]) percMostCommon.append(0) perc5MostCommon.append(0) percAncestralAllele.append(0) continue num = list(v.alleleNum[d][1:]) # number of alleles numAllele.append(len(num) - num.count(0) ) # effective number of alleles effNumAllele.append(overallFreq[-1]*overallFreq[-1]/sum( [x*x for x in v.alleleFreq[d][1:] ])) #effNumAllele.append(1./sum( [x*x for x in pop.dvars().alleleFreq[d][1:] ])-1) # count percentage of alleles derived from alleles before expansion allNum = sum(num) ancNum = 0 if len(allelesBeforeExpansion) > 0: for al in allelesBeforeExpansion[d]: try: ancNum += num[al-2] except: pass percAncestralAllele.append(ancNum*1./allNum) # percentage of each one sumAllele = sum(num)*1. percNonZero = [0]*min(highest, len(num)) # python 2.4 can do sort(reverse=True) num.sort() num.reverse() for n in range(min(len(num), highest)): percNonZero[n] = num[n]/sumAllele perc.append(percNonZero) percMostCommon.append(perc[-1][0]*100) perc5MostCommon.append(sum(perc[-1][0:5])*100) return( [perc, numAllele, effNumAllele, overallFreq, percMostCommon, perc5MostCommon, percAncestralAllele] )
|
MODU_INFO[modu]['libraries'] = ['libboost_serialization-mgw-mt-s-1_33_1', 'libboost_iostreams-mgw-mt-s-1_33_1', 'stdc++']
|
MODU_INFO[modu]['libraries'] = ['libboost_serialization-%s' % TOOLSET, 'libboost_iostreams-%s' % TOOLSET]
|
def swig_version(): ''' get the version of swig ''' fout = os.popen('swig -version') # try: version = re.match('SWIG Version\s*(\d+).(\d+).(\d+).*', fout.readlines()[1]).groups() except: print 'Can not obtain swig version, please install swig' sys.exit(1) return map(int, version)
|
MODU_INFO[modu]['libraries'] = ['boost_serialization-%s' % TOOLSET, 'boost_iostreams-%s' % TOOLSET, 'stdc++']
|
MODU_INFO[modu]['libraries'] = ['boost_serialization', 'boost_iostreams', 'stdc++']
|
def swig_version(): ''' get the version of swig ''' fout = os.popen('swig -version') # try: version = re.match('SWIG Version\s*(\d+).(\d+).(\d+).*', fout.readlines()[1]).groups() except: print 'Can not obtain swig version, please install swig' sys.exit(1) return map(int, version)
|
self.assertEqual(simu.pop(0).indInfo('info1'), tuple([6.0]*10)) self.assertEqual(simu.pop(0).indInfo('info2'), tuple([12.]*10))
|
self.assertEqual(simu.population(0).indInfo('info1'), tuple([6.0]*10)) self.assertEqual(simu.population(0).indInfo('info2'), tuple([12.]*10))
|
def indFunc1(ind, param): 'do something to info2' ind.setInfo(ind.info('info2')+param[1], 'info2') return True
|
MODU_INFO[modu]['src'].extend(GSL_FILES + SERIAL_FILES + IOSTREAMS_FILES)
|
def buildStaticLibrary(sourceFiles, libName, libDir, compiler): '''Build libraries to be linked to simuPOP modules''' # get a c compiler print 'Creating library', libName comp = new_compiler(compiler=compiler, verbose=True) objFiles = comp.compile(sourceFiles, include_dirs=['.']) comp.create_static_lib(objFiles, libName, libDir)
|
|
if modu in src:
|
if '_'+modu in src:
|
def buildStaticLibrary(sourceFiles, libName, libDir, compiler): '''Build libraries to be linked to simuPOP modules''' # get a c compiler print 'Creating library', libName comp = new_compiler(compiler=compiler, verbose=True) objFiles = comp.compile(sourceFiles, include_dirs=['.']) comp.create_static_lib(objFiles, libName, libDir)
|
toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL]
|
toCtrDist = [abs(pop.locusPos(x)-numLoci/2) for x in DSL]
|
def outputStatistics(pop, args): ''' this function will be working with a pyOperator to output statistics. Many parameters will be passed, packed as a tuple. We need to output 1. LD (D') from a central marker to all others on a non-DSL chromosome, at burnin and before and after migration 2. LD (D') from a central DSL to all others, at burnin and end 3. Fst before and after migration 4. allele frequency at DSL 5. Mean observed heterogeneity at the marker loci ''' # unwrap parameter (burnin, split, mixing, endGen, outfile) = args # gen = pop.gen() # see how long the simulation has been running if gen == burnin: print "Start introducing disease\t\t" elif gen == split: print "Start no-migration stage\t\t" elif gen == mixing: print "Start mixing\t\t" elif gen == endGen: print "End of simulation. \n" # #### preparations # number of loci when not counting DSL numLoci = pop.dvars().numLoci # non DSL loci, for convenience nonDSL = range( pop.totNumLoci() ) DSL = pop.dvars().DSL for loc in DSL: nonDSL.remove(loc) # In this analysis, we also need to know # 1. a DSL that is closest to the center of a chromosome toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL] ctrChromDSL = DSL[ [x==min(toCtrDist) for x in toCtrDist].index(True)] ctrChrom = pop.chromLocusPair(ctrChromDSL)[0] # 2. first chromosome without DSL try: noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) except: # there is no such chromosome! noDSLChrom = -1 # # loci pairs on the selected chromosomes when calculating LD i = pop.chromBegin( ctrChrom) ctrDSLLD = [ [x, ctrChromDSL] for x in range(i, ctrChromDSL)] + \ [ [ctrChromDSL, x] for x in range(ctrChromDSL+1, i+numLoci+1)] if noDSLChrom > -1: i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] else: noDSLLD = [] # save these info for later use (a plotting function will # use these info. pop.dvars().ctrChrom = ctrChrom pop.dvars().ctrChromDSL = ctrChromDSL pop.dvars().ctrDSLLD = ctrDSLLD pop.dvars().noDSLChrom = noDSLChrom pop.dvars().noDSLLD = noDSLLD # #@@@ NOW, output statistics # append to output file. output = open(outfile, 'a') # first, calculate LD and other statistics Stat(pop, alleleFreq=DSL, LD = ctrDSLLD + noDSLLD, Fst = nonDSL, heteroFreq = range( pop.totNumLoci() ) ) # output D', allele frequency at split, mixing and endGen if gen in [split, mixing, endGen]: print >> output, "Average Fst estimated from non-DSL at gen %d: %.4f \n" % (gen, pop.dvars().AvgFst) print >> output, "D between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], if noDSLChrom > -1 : print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD' between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], if noDSLChrom > -1: print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nAllele frequencies\nall\t", for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars().alleleFreq[d][1]), for sp in range(numSubPop): print >> output, "\n%d\t" % sp, for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars(sp).alleleFreq[d][1]), print >> output, "\n", # hetero frequency AvgHetero = 0 for d in range(pop.totNumLoci()): AvgHetero += pop.dvars().heteroFreq[d][0] AvgHetero /= pop.totNumLoci() # save to pop pop.dvars().AvgHetero = AvgHetero # output it print >> output, '\nAverage counted heterozygosity is %.4f.\n' % AvgHetero return True
|
lociDist = []
|
lociPos = []
|
def simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile): ''' run a simulation of complex disease with given parameters. ''' if markerType == 'microsatellite': maxAle = 99 # max allele else: maxAle = 2 # SNP #### translate numChrom, numLoci, DSLafterLoci to #### loci, lociDist, DSL, nonDSL in the usual index #### (count markers along with DSL) numDSL = len(DSLafter) if len(DSLdist) != numDSL: raise exceptions.ValueError("--DSL and --DSLloc has different length.") # real indices of DSL DSL = list(DSLafter) for i in range(0,numDSL): DSL[i] += i+1 # adjust loci and lociDist loci = [0]*numChrom lociDist = [] i = 0 # current absolute locus j = 0 # current DSL for ch in range(0, numChrom): lociDist.append([]) for loc in range(0,numLoci): # DSL after original loci indices if j < numDSL and i == DSLafter[j]: loci[ch] += 2 lociDist[ch].append(loc+1) lociDist[ch].append(loc+1 + DSLdist[j]) j += 1 else: loci[ch] += 1 lociDist[ch].append(loc+1) i += 1 # non DSL loci, for convenience nonDSL = range(0, reduce(operator.add, loci)) for loc in DSL: nonDSL.remove(loc) #### Change generation duration to point split = burnin + introGen mixing = split + noMigrGen endGen = mixing + mixingGen #### initialization and mutation if maxAle > 2: # Not SNP preOperators = [ # initialize all loci with 5 haplotypes initByValue(value=[[x]*reduce(operator.add, loci) \ for x in range(meanInitAllele-2, meanInitAllele+3)], proportions=[.2]*5), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # symmetric mutation model for microsatellite mutator = smmMutator(rate=mu, maxAllele=maxAle, atLoci=nonDSL) else: # SNP preOperators = [ # initialize all loci with two haplotypes (111,222) initByValue(value=[[x]*reduce(operator.add, loci) for x in range(1,3)], proportions=[.5]*2), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # k-allele model for mutation of SNP mutator = kamMutator(rate=mu, maxAllele=2, atLoci=nonDSL) #### burn in stage # mutation and recombination will always be in effective # so we do not have to specify them later operators = [ # mutator, differ by marker type mutator, # recombination, use intensity since loci (include DSL) # are not equally spaced recombinator(intensity=rec), ] #### disease introduction stage operators.extend( [ # need to measure allele frequency at DSL stat(alleleFreq=DSL, popSize=True, begin = burnin), pyEval( expr=r'"%d(%d): "%(gen, popSize) + " ".join(["%.3f"%(1-alleleFreq[x][1]) for x in DSL])+"\n"', begin = burnin) ] ) # need five conditional point mutator to # introduce disease. It does not matter that we introduce # mutant specifically to individuel i since individuals # are unordered for i in range(numDSL): # this operator literally says: if there is no DS allele, # introduce one. Note that operator stat has to be called # before this one. operators.append( ifElse("alleleFreq[%d][1]==1." % DSL[i], pointMutator(atLoci=[DSL[i]], toAllele=2, inds=[i]), begin=burnin, end=split) ) # # use selective pressure to let allele frequency reach # [minAlleleFreq, maxAlleleFreq]. operators.append( pyOperator( func=dynaAdvSelector, stage=PreMating, begin=burnin, end=split) ) # check if allele frequency has reached desired value (loosely judged by 4/5*min) for i in range(len(DSL)): operators.append( terminateIf("1-alleleFreq[%d][1]<%f" % (DSL[i], minAlleleFreq[i]*4/5.), at=[split]) ) #### no migration stage if numSubPop > 1: operators.append( # split population after burnin, to each sized subpopulations splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[split]), ) # # start selection if mlSelModel != SEL_None: operators.append( mlSelector( # with five multiple-allele selector as parameter [ maSelector(locus=DSL[x], wildtype=[1], fitness=fitness[x]) for x in range(len(DSL)) ], mode=mlSelModel, begin=split), ) # ### mixing stage # a migrator, stepping stone or island if numSubPop > 1 and migrModel == 'island' and mi > 0: operators.append( migrator(migrIslandRates(mi, numSubPop), mode=MigrByProbability, begin=mixing) ) elif numSubPop > 1 and migrModel == 'stepping stone' and mi > 0: operators.append( migrator(migrSteppingStoneRates(mi, numSubPop, circular=True), mode=MigrByProbability, begin=mixing) ) # # prepare for sampling: # use last_two numOffspringFunc, simuPOP will produce 2 offspring at # the last two generations, this is when we should store parental # information and trace pedigree info # operators.extend([ # save ancestral populations starting at -2 gen setAncestralDepth(2, at=[-2]), # track pedigree parentsTagger(begin=-2), # terminate simulation is on DSL get lost. terminateIf("True in [alleleFreq[x][1] == 1 for x in DSL]", begin=split), # output statistics pyOperator(func=outputStatistics, param = (burnin, split, mixing, endGen, logFile), at = [burnin, split, mixing, endGen] ), # Show how long the program has been running. pyEval(r'"Burn-in stage: generation %d\n" % gen ', step = 10, end=burnin), # show elapsed time ticToc(at=[burnin, split, mixing, endGen]), ] ) # with all operators, we can set up a simulator # # produce two offsprings only at the last generations. def last_two(gen): if gen >= endGen -2: return 2 else: return 1 # may need to run several times to # get a valid population (terminate if any DSL has no disease allele) fixedCount = 1 while(True): # create a simulator pop = population(subPop=popSizeFunc(0), ploidy=2, loci = loci, maxAllele = maxAle, lociDist = lociDist) # save DSL info, some operators will use it. pop.dvars().DSL = DSL pop.dvars().numLoci = numLoci pop.dvars().minAlleleFreq = minAlleleFreq pop.dvars().maxAlleleFreq = maxAlleleFreq # clear log file if it exists try: os.remove(logFile) except: pass # start simulation. simu = simulator( pop, randomMating( newSubPopSizeFunc=popSizeFunc, # demographic model numOffspringFunc=last_two), # save last two generations rep=1) # evolve! If --dryrun is set, only show info simu.evolve( preOps = preOperators, ops = operators, end=endGen, dryrun=dryrun ) if dryrun: raise exceptions.SystemError("Stop since in dryrun mode.") # if succeed if simu.gen() == endGen + 1: # if not fixed pop = simu.population(0) # we want to save info on how this population is generated. # This is not required but is a good practise pop.dvars().DSLAfter = DSLafter pop.dvars().DSLdist = DSLdist pop.dvars().initSize = initSize pop.dvars().meanInitAllele = meanInitAllele pop.dvars().finalSize = finalSize pop.dvars().burnin = burnin pop.dvars().introGen = introGen pop.dvars().numSubPop = numSubPop pop.dvars().noMigrGen = noMigrGen pop.dvars().mixingGen = mixingGen pop.dvars().mutationRate = mu pop.dvars().mutationModel = "symmetric stepwise" pop.dvars().migrationRate = mi pop.dvars().migrationModel = "circular stepping stone" pop.dvars().recombinationRate = rec # return a copy (and then simulator will be destroyed) #return simu.getPopulation(0) # simu will be destroyed after return, however, simu.getPopulation # will make a copy of population(0) and double the use of memory # at this time.... this will cause problem when population size # is large. # I am using a trick here, namely, create a small population and # swap out the population in simulator. This is undocumented # and should be avoid whenever possible tmpPop = population(1) tmpPop.swap(simu.population(0)) return tmpPop else: print "Population restarted at gen ", simu.gen() print "Overall fixed population ", fixedCount print "Allelefreq ", ( "%.3f " * numDSL + "\n\n") % \ tuple([1-simu.dvars(0).alleleFreq[x][1] for x in DSL]) fixedCount += 1
|
lociDist.append([])
|
lociPos.append([])
|
def simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile): ''' run a simulation of complex disease with given parameters. ''' if markerType == 'microsatellite': maxAle = 99 # max allele else: maxAle = 2 # SNP #### translate numChrom, numLoci, DSLafterLoci to #### loci, lociDist, DSL, nonDSL in the usual index #### (count markers along with DSL) numDSL = len(DSLafter) if len(DSLdist) != numDSL: raise exceptions.ValueError("--DSL and --DSLloc has different length.") # real indices of DSL DSL = list(DSLafter) for i in range(0,numDSL): DSL[i] += i+1 # adjust loci and lociDist loci = [0]*numChrom lociDist = [] i = 0 # current absolute locus j = 0 # current DSL for ch in range(0, numChrom): lociDist.append([]) for loc in range(0,numLoci): # DSL after original loci indices if j < numDSL and i == DSLafter[j]: loci[ch] += 2 lociDist[ch].append(loc+1) lociDist[ch].append(loc+1 + DSLdist[j]) j += 1 else: loci[ch] += 1 lociDist[ch].append(loc+1) i += 1 # non DSL loci, for convenience nonDSL = range(0, reduce(operator.add, loci)) for loc in DSL: nonDSL.remove(loc) #### Change generation duration to point split = burnin + introGen mixing = split + noMigrGen endGen = mixing + mixingGen #### initialization and mutation if maxAle > 2: # Not SNP preOperators = [ # initialize all loci with 5 haplotypes initByValue(value=[[x]*reduce(operator.add, loci) \ for x in range(meanInitAllele-2, meanInitAllele+3)], proportions=[.2]*5), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # symmetric mutation model for microsatellite mutator = smmMutator(rate=mu, maxAllele=maxAle, atLoci=nonDSL) else: # SNP preOperators = [ # initialize all loci with two haplotypes (111,222) initByValue(value=[[x]*reduce(operator.add, loci) for x in range(1,3)], proportions=[.5]*2), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # k-allele model for mutation of SNP mutator = kamMutator(rate=mu, maxAllele=2, atLoci=nonDSL) #### burn in stage # mutation and recombination will always be in effective # so we do not have to specify them later operators = [ # mutator, differ by marker type mutator, # recombination, use intensity since loci (include DSL) # are not equally spaced recombinator(intensity=rec), ] #### disease introduction stage operators.extend( [ # need to measure allele frequency at DSL stat(alleleFreq=DSL, popSize=True, begin = burnin), pyEval( expr=r'"%d(%d): "%(gen, popSize) + " ".join(["%.3f"%(1-alleleFreq[x][1]) for x in DSL])+"\n"', begin = burnin) ] ) # need five conditional point mutator to # introduce disease. It does not matter that we introduce # mutant specifically to individuel i since individuals # are unordered for i in range(numDSL): # this operator literally says: if there is no DS allele, # introduce one. Note that operator stat has to be called # before this one. operators.append( ifElse("alleleFreq[%d][1]==1." % DSL[i], pointMutator(atLoci=[DSL[i]], toAllele=2, inds=[i]), begin=burnin, end=split) ) # # use selective pressure to let allele frequency reach # [minAlleleFreq, maxAlleleFreq]. operators.append( pyOperator( func=dynaAdvSelector, stage=PreMating, begin=burnin, end=split) ) # check if allele frequency has reached desired value (loosely judged by 4/5*min) for i in range(len(DSL)): operators.append( terminateIf("1-alleleFreq[%d][1]<%f" % (DSL[i], minAlleleFreq[i]*4/5.), at=[split]) ) #### no migration stage if numSubPop > 1: operators.append( # split population after burnin, to each sized subpopulations splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[split]), ) # # start selection if mlSelModel != SEL_None: operators.append( mlSelector( # with five multiple-allele selector as parameter [ maSelector(locus=DSL[x], wildtype=[1], fitness=fitness[x]) for x in range(len(DSL)) ], mode=mlSelModel, begin=split), ) # ### mixing stage # a migrator, stepping stone or island if numSubPop > 1 and migrModel == 'island' and mi > 0: operators.append( migrator(migrIslandRates(mi, numSubPop), mode=MigrByProbability, begin=mixing) ) elif numSubPop > 1 and migrModel == 'stepping stone' and mi > 0: operators.append( migrator(migrSteppingStoneRates(mi, numSubPop, circular=True), mode=MigrByProbability, begin=mixing) ) # # prepare for sampling: # use last_two numOffspringFunc, simuPOP will produce 2 offspring at # the last two generations, this is when we should store parental # information and trace pedigree info # operators.extend([ # save ancestral populations starting at -2 gen setAncestralDepth(2, at=[-2]), # track pedigree parentsTagger(begin=-2), # terminate simulation is on DSL get lost. terminateIf("True in [alleleFreq[x][1] == 1 for x in DSL]", begin=split), # output statistics pyOperator(func=outputStatistics, param = (burnin, split, mixing, endGen, logFile), at = [burnin, split, mixing, endGen] ), # Show how long the program has been running. pyEval(r'"Burn-in stage: generation %d\n" % gen ', step = 10, end=burnin), # show elapsed time ticToc(at=[burnin, split, mixing, endGen]), ] ) # with all operators, we can set up a simulator # # produce two offsprings only at the last generations. def last_two(gen): if gen >= endGen -2: return 2 else: return 1 # may need to run several times to # get a valid population (terminate if any DSL has no disease allele) fixedCount = 1 while(True): # create a simulator pop = population(subPop=popSizeFunc(0), ploidy=2, loci = loci, maxAllele = maxAle, lociDist = lociDist) # save DSL info, some operators will use it. pop.dvars().DSL = DSL pop.dvars().numLoci = numLoci pop.dvars().minAlleleFreq = minAlleleFreq pop.dvars().maxAlleleFreq = maxAlleleFreq # clear log file if it exists try: os.remove(logFile) except: pass # start simulation. simu = simulator( pop, randomMating( newSubPopSizeFunc=popSizeFunc, # demographic model numOffspringFunc=last_two), # save last two generations rep=1) # evolve! If --dryrun is set, only show info simu.evolve( preOps = preOperators, ops = operators, end=endGen, dryrun=dryrun ) if dryrun: raise exceptions.SystemError("Stop since in dryrun mode.") # if succeed if simu.gen() == endGen + 1: # if not fixed pop = simu.population(0) # we want to save info on how this population is generated. # This is not required but is a good practise pop.dvars().DSLAfter = DSLafter pop.dvars().DSLdist = DSLdist pop.dvars().initSize = initSize pop.dvars().meanInitAllele = meanInitAllele pop.dvars().finalSize = finalSize pop.dvars().burnin = burnin pop.dvars().introGen = introGen pop.dvars().numSubPop = numSubPop pop.dvars().noMigrGen = noMigrGen pop.dvars().mixingGen = mixingGen pop.dvars().mutationRate = mu pop.dvars().mutationModel = "symmetric stepwise" pop.dvars().migrationRate = mi pop.dvars().migrationModel = "circular stepping stone" pop.dvars().recombinationRate = rec # return a copy (and then simulator will be destroyed) #return simu.getPopulation(0) # simu will be destroyed after return, however, simu.getPopulation # will make a copy of population(0) and double the use of memory # at this time.... this will cause problem when population size # is large. # I am using a trick here, namely, create a small population and # swap out the population in simulator. This is undocumented # and should be avoid whenever possible tmpPop = population(1) tmpPop.swap(simu.population(0)) return tmpPop else: print "Population restarted at gen ", simu.gen() print "Overall fixed population ", fixedCount print "Allelefreq ", ( "%.3f " * numDSL + "\n\n") % \ tuple([1-simu.dvars(0).alleleFreq[x][1] for x in DSL]) fixedCount += 1
|
lociDist[ch].append(loc+1) lociDist[ch].append(loc+1 + DSLdist[j])
|
lociPos[ch].append(loc+1) lociPos[ch].append(loc+1 + DSLdist[j])
|
def simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile): ''' run a simulation of complex disease with given parameters. ''' if markerType == 'microsatellite': maxAle = 99 # max allele else: maxAle = 2 # SNP #### translate numChrom, numLoci, DSLafterLoci to #### loci, lociDist, DSL, nonDSL in the usual index #### (count markers along with DSL) numDSL = len(DSLafter) if len(DSLdist) != numDSL: raise exceptions.ValueError("--DSL and --DSLloc has different length.") # real indices of DSL DSL = list(DSLafter) for i in range(0,numDSL): DSL[i] += i+1 # adjust loci and lociDist loci = [0]*numChrom lociDist = [] i = 0 # current absolute locus j = 0 # current DSL for ch in range(0, numChrom): lociDist.append([]) for loc in range(0,numLoci): # DSL after original loci indices if j < numDSL and i == DSLafter[j]: loci[ch] += 2 lociDist[ch].append(loc+1) lociDist[ch].append(loc+1 + DSLdist[j]) j += 1 else: loci[ch] += 1 lociDist[ch].append(loc+1) i += 1 # non DSL loci, for convenience nonDSL = range(0, reduce(operator.add, loci)) for loc in DSL: nonDSL.remove(loc) #### Change generation duration to point split = burnin + introGen mixing = split + noMigrGen endGen = mixing + mixingGen #### initialization and mutation if maxAle > 2: # Not SNP preOperators = [ # initialize all loci with 5 haplotypes initByValue(value=[[x]*reduce(operator.add, loci) \ for x in range(meanInitAllele-2, meanInitAllele+3)], proportions=[.2]*5), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # symmetric mutation model for microsatellite mutator = smmMutator(rate=mu, maxAllele=maxAle, atLoci=nonDSL) else: # SNP preOperators = [ # initialize all loci with two haplotypes (111,222) initByValue(value=[[x]*reduce(operator.add, loci) for x in range(1,3)], proportions=[.5]*2), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # k-allele model for mutation of SNP mutator = kamMutator(rate=mu, maxAllele=2, atLoci=nonDSL) #### burn in stage # mutation and recombination will always be in effective # so we do not have to specify them later operators = [ # mutator, differ by marker type mutator, # recombination, use intensity since loci (include DSL) # are not equally spaced recombinator(intensity=rec), ] #### disease introduction stage operators.extend( [ # need to measure allele frequency at DSL stat(alleleFreq=DSL, popSize=True, begin = burnin), pyEval( expr=r'"%d(%d): "%(gen, popSize) + " ".join(["%.3f"%(1-alleleFreq[x][1]) for x in DSL])+"\n"', begin = burnin) ] ) # need five conditional point mutator to # introduce disease. It does not matter that we introduce # mutant specifically to individuel i since individuals # are unordered for i in range(numDSL): # this operator literally says: if there is no DS allele, # introduce one. Note that operator stat has to be called # before this one. operators.append( ifElse("alleleFreq[%d][1]==1." % DSL[i], pointMutator(atLoci=[DSL[i]], toAllele=2, inds=[i]), begin=burnin, end=split) ) # # use selective pressure to let allele frequency reach # [minAlleleFreq, maxAlleleFreq]. operators.append( pyOperator( func=dynaAdvSelector, stage=PreMating, begin=burnin, end=split) ) # check if allele frequency has reached desired value (loosely judged by 4/5*min) for i in range(len(DSL)): operators.append( terminateIf("1-alleleFreq[%d][1]<%f" % (DSL[i], minAlleleFreq[i]*4/5.), at=[split]) ) #### no migration stage if numSubPop > 1: operators.append( # split population after burnin, to each sized subpopulations splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[split]), ) # # start selection if mlSelModel != SEL_None: operators.append( mlSelector( # with five multiple-allele selector as parameter [ maSelector(locus=DSL[x], wildtype=[1], fitness=fitness[x]) for x in range(len(DSL)) ], mode=mlSelModel, begin=split), ) # ### mixing stage # a migrator, stepping stone or island if numSubPop > 1 and migrModel == 'island' and mi > 0: operators.append( migrator(migrIslandRates(mi, numSubPop), mode=MigrByProbability, begin=mixing) ) elif numSubPop > 1 and migrModel == 'stepping stone' and mi > 0: operators.append( migrator(migrSteppingStoneRates(mi, numSubPop, circular=True), mode=MigrByProbability, begin=mixing) ) # # prepare for sampling: # use last_two numOffspringFunc, simuPOP will produce 2 offspring at # the last two generations, this is when we should store parental # information and trace pedigree info # operators.extend([ # save ancestral populations starting at -2 gen setAncestralDepth(2, at=[-2]), # track pedigree parentsTagger(begin=-2), # terminate simulation is on DSL get lost. terminateIf("True in [alleleFreq[x][1] == 1 for x in DSL]", begin=split), # output statistics pyOperator(func=outputStatistics, param = (burnin, split, mixing, endGen, logFile), at = [burnin, split, mixing, endGen] ), # Show how long the program has been running. pyEval(r'"Burn-in stage: generation %d\n" % gen ', step = 10, end=burnin), # show elapsed time ticToc(at=[burnin, split, mixing, endGen]), ] ) # with all operators, we can set up a simulator # # produce two offsprings only at the last generations. def last_two(gen): if gen >= endGen -2: return 2 else: return 1 # may need to run several times to # get a valid population (terminate if any DSL has no disease allele) fixedCount = 1 while(True): # create a simulator pop = population(subPop=popSizeFunc(0), ploidy=2, loci = loci, maxAllele = maxAle, lociDist = lociDist) # save DSL info, some operators will use it. pop.dvars().DSL = DSL pop.dvars().numLoci = numLoci pop.dvars().minAlleleFreq = minAlleleFreq pop.dvars().maxAlleleFreq = maxAlleleFreq # clear log file if it exists try: os.remove(logFile) except: pass # start simulation. simu = simulator( pop, randomMating( newSubPopSizeFunc=popSizeFunc, # demographic model numOffspringFunc=last_two), # save last two generations rep=1) # evolve! If --dryrun is set, only show info simu.evolve( preOps = preOperators, ops = operators, end=endGen, dryrun=dryrun ) if dryrun: raise exceptions.SystemError("Stop since in dryrun mode.") # if succeed if simu.gen() == endGen + 1: # if not fixed pop = simu.population(0) # we want to save info on how this population is generated. # This is not required but is a good practise pop.dvars().DSLAfter = DSLafter pop.dvars().DSLdist = DSLdist pop.dvars().initSize = initSize pop.dvars().meanInitAllele = meanInitAllele pop.dvars().finalSize = finalSize pop.dvars().burnin = burnin pop.dvars().introGen = introGen pop.dvars().numSubPop = numSubPop pop.dvars().noMigrGen = noMigrGen pop.dvars().mixingGen = mixingGen pop.dvars().mutationRate = mu pop.dvars().mutationModel = "symmetric stepwise" pop.dvars().migrationRate = mi pop.dvars().migrationModel = "circular stepping stone" pop.dvars().recombinationRate = rec # return a copy (and then simulator will be destroyed) #return simu.getPopulation(0) # simu will be destroyed after return, however, simu.getPopulation # will make a copy of population(0) and double the use of memory # at this time.... this will cause problem when population size # is large. # I am using a trick here, namely, create a small population and # swap out the population in simulator. This is undocumented # and should be avoid whenever possible tmpPop = population(1) tmpPop.swap(simu.population(0)) return tmpPop else: print "Population restarted at gen ", simu.gen() print "Overall fixed population ", fixedCount print "Allelefreq ", ( "%.3f " * numDSL + "\n\n") % \ tuple([1-simu.dvars(0).alleleFreq[x][1] for x in DSL]) fixedCount += 1
|
lociDist[ch].append(loc+1)
|
lociPos[ch].append(loc+1)
|
def simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile): ''' run a simulation of complex disease with given parameters. ''' if markerType == 'microsatellite': maxAle = 99 # max allele else: maxAle = 2 # SNP #### translate numChrom, numLoci, DSLafterLoci to #### loci, lociDist, DSL, nonDSL in the usual index #### (count markers along with DSL) numDSL = len(DSLafter) if len(DSLdist) != numDSL: raise exceptions.ValueError("--DSL and --DSLloc has different length.") # real indices of DSL DSL = list(DSLafter) for i in range(0,numDSL): DSL[i] += i+1 # adjust loci and lociDist loci = [0]*numChrom lociDist = [] i = 0 # current absolute locus j = 0 # current DSL for ch in range(0, numChrom): lociDist.append([]) for loc in range(0,numLoci): # DSL after original loci indices if j < numDSL and i == DSLafter[j]: loci[ch] += 2 lociDist[ch].append(loc+1) lociDist[ch].append(loc+1 + DSLdist[j]) j += 1 else: loci[ch] += 1 lociDist[ch].append(loc+1) i += 1 # non DSL loci, for convenience nonDSL = range(0, reduce(operator.add, loci)) for loc in DSL: nonDSL.remove(loc) #### Change generation duration to point split = burnin + introGen mixing = split + noMigrGen endGen = mixing + mixingGen #### initialization and mutation if maxAle > 2: # Not SNP preOperators = [ # initialize all loci with 5 haplotypes initByValue(value=[[x]*reduce(operator.add, loci) \ for x in range(meanInitAllele-2, meanInitAllele+3)], proportions=[.2]*5), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # symmetric mutation model for microsatellite mutator = smmMutator(rate=mu, maxAllele=maxAle, atLoci=nonDSL) else: # SNP preOperators = [ # initialize all loci with two haplotypes (111,222) initByValue(value=[[x]*reduce(operator.add, loci) for x in range(1,3)], proportions=[.5]*2), # and then init DSL with all wild type alleles initByValue([1]*len(DSL), atLoci=DSL) ] # k-allele model for mutation of SNP mutator = kamMutator(rate=mu, maxAllele=2, atLoci=nonDSL) #### burn in stage # mutation and recombination will always be in effective # so we do not have to specify them later operators = [ # mutator, differ by marker type mutator, # recombination, use intensity since loci (include DSL) # are not equally spaced recombinator(intensity=rec), ] #### disease introduction stage operators.extend( [ # need to measure allele frequency at DSL stat(alleleFreq=DSL, popSize=True, begin = burnin), pyEval( expr=r'"%d(%d): "%(gen, popSize) + " ".join(["%.3f"%(1-alleleFreq[x][1]) for x in DSL])+"\n"', begin = burnin) ] ) # need five conditional point mutator to # introduce disease. It does not matter that we introduce # mutant specifically to individuel i since individuals # are unordered for i in range(numDSL): # this operator literally says: if there is no DS allele, # introduce one. Note that operator stat has to be called # before this one. operators.append( ifElse("alleleFreq[%d][1]==1." % DSL[i], pointMutator(atLoci=[DSL[i]], toAllele=2, inds=[i]), begin=burnin, end=split) ) # # use selective pressure to let allele frequency reach # [minAlleleFreq, maxAlleleFreq]. operators.append( pyOperator( func=dynaAdvSelector, stage=PreMating, begin=burnin, end=split) ) # check if allele frequency has reached desired value (loosely judged by 4/5*min) for i in range(len(DSL)): operators.append( terminateIf("1-alleleFreq[%d][1]<%f" % (DSL[i], minAlleleFreq[i]*4/5.), at=[split]) ) #### no migration stage if numSubPop > 1: operators.append( # split population after burnin, to each sized subpopulations splitSubPop(0, proportions=[1./numSubPop]*numSubPop, at=[split]), ) # # start selection if mlSelModel != SEL_None: operators.append( mlSelector( # with five multiple-allele selector as parameter [ maSelector(locus=DSL[x], wildtype=[1], fitness=fitness[x]) for x in range(len(DSL)) ], mode=mlSelModel, begin=split), ) # ### mixing stage # a migrator, stepping stone or island if numSubPop > 1 and migrModel == 'island' and mi > 0: operators.append( migrator(migrIslandRates(mi, numSubPop), mode=MigrByProbability, begin=mixing) ) elif numSubPop > 1 and migrModel == 'stepping stone' and mi > 0: operators.append( migrator(migrSteppingStoneRates(mi, numSubPop, circular=True), mode=MigrByProbability, begin=mixing) ) # # prepare for sampling: # use last_two numOffspringFunc, simuPOP will produce 2 offspring at # the last two generations, this is when we should store parental # information and trace pedigree info # operators.extend([ # save ancestral populations starting at -2 gen setAncestralDepth(2, at=[-2]), # track pedigree parentsTagger(begin=-2), # terminate simulation is on DSL get lost. terminateIf("True in [alleleFreq[x][1] == 1 for x in DSL]", begin=split), # output statistics pyOperator(func=outputStatistics, param = (burnin, split, mixing, endGen, logFile), at = [burnin, split, mixing, endGen] ), # Show how long the program has been running. pyEval(r'"Burn-in stage: generation %d\n" % gen ', step = 10, end=burnin), # show elapsed time ticToc(at=[burnin, split, mixing, endGen]), ] ) # with all operators, we can set up a simulator # # produce two offsprings only at the last generations. def last_two(gen): if gen >= endGen -2: return 2 else: return 1 # may need to run several times to # get a valid population (terminate if any DSL has no disease allele) fixedCount = 1 while(True): # create a simulator pop = population(subPop=popSizeFunc(0), ploidy=2, loci = loci, maxAllele = maxAle, lociDist = lociDist) # save DSL info, some operators will use it. pop.dvars().DSL = DSL pop.dvars().numLoci = numLoci pop.dvars().minAlleleFreq = minAlleleFreq pop.dvars().maxAlleleFreq = maxAlleleFreq # clear log file if it exists try: os.remove(logFile) except: pass # start simulation. simu = simulator( pop, randomMating( newSubPopSizeFunc=popSizeFunc, # demographic model numOffspringFunc=last_two), # save last two generations rep=1) # evolve! If --dryrun is set, only show info simu.evolve( preOps = preOperators, ops = operators, end=endGen, dryrun=dryrun ) if dryrun: raise exceptions.SystemError("Stop since in dryrun mode.") # if succeed if simu.gen() == endGen + 1: # if not fixed pop = simu.population(0) # we want to save info on how this population is generated. # This is not required but is a good practise pop.dvars().DSLAfter = DSLafter pop.dvars().DSLdist = DSLdist pop.dvars().initSize = initSize pop.dvars().meanInitAllele = meanInitAllele pop.dvars().finalSize = finalSize pop.dvars().burnin = burnin pop.dvars().introGen = introGen pop.dvars().numSubPop = numSubPop pop.dvars().noMigrGen = noMigrGen pop.dvars().mixingGen = mixingGen pop.dvars().mutationRate = mu pop.dvars().mutationModel = "symmetric stepwise" pop.dvars().migrationRate = mi pop.dvars().migrationModel = "circular stepping stone" pop.dvars().recombinationRate = rec # return a copy (and then simulator will be destroyed) #return simu.getPopulation(0) # simu will be destroyed after return, however, simu.getPopulation # will make a copy of population(0) and double the use of memory # at this time.... this will cause problem when population size # is large. # I am using a trick here, namely, create a small population and # swap out the population in simulator. This is undocumented # and should be avoid whenever possible tmpPop = population(1) tmpPop.swap(simu.population(0)) return tmpPop else: print "Population restarted at gen ", simu.gen() print "Overall fixed population ", fixedCount print "Allelefreq ", ( "%.3f " * numDSL + "\n\n") % \ tuple([1-simu.dvars(0).alleleFreq[x][1] for x in DSL]) fixedCount += 1
|
loci = loci, maxAllele = maxAle, lociDist = lociDist)
|
loci = loci, maxAllele = maxAle, lociPos = lociPos)
|
def last_two(gen): if gen >= endGen -2: return 2 else: return 1
|
dist.append(pop.locusDist(ld[0]))
|
dist.append(pop.locusPos(ld[0]))
|
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' # return max LD res = {} # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpDSL'] = max(ldprime) res['DDSL'] = max(ldvalue) if hasRPy: r.postscript(file=epsFile, width=8, height=8) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % (pop.dvars().ctrChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] # D' ldvalue = [] # D if pop.dvars().noDSLChrom > -1: for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() else: res['DpNon'] = 0 res['DNon'] = 0 if hasRPy: r.plot( 0, 0, main="There is no chromosome without DSL", xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
dist.append(pop.locusDist(ld[1]))
|
dist.append(pop.locusPos(ld[1]))
|
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' # return max LD res = {} # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpDSL'] = max(ldprime) res['DDSL'] = max(ldvalue) if hasRPy: r.postscript(file=epsFile, width=8, height=8) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % (pop.dvars().ctrChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] # D' ldvalue = [] # D if pop.dvars().noDSLChrom > -1: for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() else: res['DpNon'] = 0 res['DNon'] = 0 if hasRPy: r.plot( 0, 0, main="There is no chromosome without DSL", xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL'])
|
r.abline( v = pop.locusPos(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusPos(pop.dvars().ctrChromDSL)], ['DSL'])
|
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' # return max LD res = {} # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpDSL'] = max(ldprime) res['DDSL'] = max(ldvalue) if hasRPy: r.postscript(file=epsFile, width=8, height=8) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % (pop.dvars().ctrChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] # D' ldvalue = [] # D if pop.dvars().noDSLChrom > -1: for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() else: res['DpNon'] = 0 res['DNon'] = 0 if hasRPy: r.plot( 0, 0, main="There is no chromosome without DSL", xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 )
|
r.abline( v = pop.locusPos(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 )
|
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' # return max LD res = {} # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpDSL'] = max(ldprime) res['DDSL'] = max(ldvalue) if hasRPy: r.postscript(file=epsFile, width=8, height=8) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % (pop.dvars().ctrChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] # D' ldvalue = [] # D if pop.dvars().noDSLChrom > -1: for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() else: res['DpNon'] = 0 res['DNon'] = 0 if hasRPy: r.plot( 0, 0, main="There is no chromosome without DSL", xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
summary.write('<th>K</th><th>Ks</th><th>Ks/K</th>') summary.write('<th>P11</th><th>P12</th><th>P22</th>') summary.write("<th>F'</th>")
|
def writeReport(content, allParam, numChrom, numLoci, DSLafter, peneFunc, numSample, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method, + for exceeds and - for less than cutoff value -log10(pvalue/total number of loci) ) at all relevant DSL. The cutoff is chosen as -log10(0.05/number of loci) which is the Bonferroni correction. Other statistics include K (population prevalence), Ks (sibling recurrance risk), Ls=Ks/K (lambda_s, sibling recurrance ratio), P11 (P(NN | affected)), P12 (P(NS | affected)), P13 (P(SS|affected)), F' = P(disease allele | affected) = allele frequency among affected individuals.</p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(DSLafter)): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(peneFunc) > 0: summary.write('<th>K</th><th>Ks</th><th>Ks/K</th>') summary.write('<th>P11</th><th>P12</th><th>P22</th>') summary.write("<th>F'</th>") for p in peneFunc: for met in ['TDT', 'LOD']: for num in range(numSample): # samples summary.write('<th>%s:%s-%d</th>'%(p,met,num)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.3g</td>' % res['Fst']) summary.write('<td>%.3g</td>' % res['AvgHet']) summary.write('<td>%.3g</td>' % res['DpDSL']) summary.write('<td>%.3g</td>' % res['DDSL']) summary.write('<td>%.3g</td>' % res['DpNon']) summary.write('<td>%.3g</td>' % res['DNon']) for i in range(len(DSLafter)): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(peneFunc) > 0: for p in peneFunc: # penetrance function summary.write('<td>%.3g</td>' % res[p+'_K']) summary.write('<td>%.3g</td>' % res[p+'_Ks']) summary.write('<td>%.3g</td>' % res[p+'_Ls']) summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P11'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P12'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P22'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_Fprime'] ]) + '</td>') for met in ['TDT', 'LOD']: for num in range(numSample): # samples plusMinus = '' for pvalue in res[met+'_'+p+'_'+str(num)]: if pvalue > -math.log10(0.05/(numChrom*numLoci)): plusMinus += '+' else: plusMinus += '-' summary.write('<td>'+plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
|
noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True)
|
try: noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) except: noDSLChrom = -1
|
def outputStatistics(pop, args): ''' this function will be working with a pyOperator to output statistics. Many parameters will be passed, packed as a tuple. We need to output 1. LD (D') from a central marker to all others on a non-DSL chromosome, at burnin and before and after migration 2. LD (D') from a central DSL to all others, at burnin and end 3. Fst before and after migration 4. allele frequency at DSL 5. Mean observed heterogeneity at the marker loci ''' # unwrap parameter (burnin, split, mixing, endGen, outfile) = args # gen = pop.gen() # see how long the simulation has been running if gen == burnin: print "Start introducing disease\t\t" elif gen == split: print "Start no-migration stage\t\t" elif gen == mixing: print "Start mixing\t\t" elif gen == endGen: print "End of simulation. \n" # #### preparations # number of loci when not counting DSL numLoci = pop.dvars().numLoci # non DSL loci, for convenience nonDSL = range( pop.totNumLoci() ) DSL = pop.dvars().DSL for loc in DSL: nonDSL.remove(loc) # In this analysis, we also need to know # 1. a DSL that is closest to the center of a chromosome toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL] ctrChromDSL = DSL[ [x==min(toCtrDist) for x in toCtrDist].index(True)] ctrChrom = pop.chromLocusPair(ctrChromDSL)[0] # 2. first chromosome without DSL noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) # # loci pairs on the selected chromosomes when calculating LD i = pop.chromBegin( ctrChrom) ctrDSLLD = [ [x, ctrChromDSL] for x in range(i, ctrChromDSL)] + \ [ [ctrChromDSL, x] for x in range(ctrChromDSL+1, i+numLoci+1)] i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] # save these info for later use (a plotting function will # use these info. pop.dvars().ctrChrom = ctrChrom pop.dvars().ctrChromDSL = ctrChromDSL pop.dvars().ctrDSLLD = ctrDSLLD pop.dvars().noDSLChrom = noDSLChrom pop.dvars().noDSLLD = noDSLLD # #@@@ NOW, output statistics # append to output file. output = open(outfile, 'a') # first, calculate LD and other statistics Stat(pop, alleleFreq=DSL, LD = ctrDSLLD + noDSLLD, Fst = nonDSL, heteroFreq = range( pop.totNumLoci() ) ) # output D', allele frequency at split, mixing and endGen if gen in [split, mixing, endGen]: print >> output, "Average Fst estimated from non-DSL at gen %d: %.4f \n" % (gen, pop.dvars().AvgFst) print >> output, "D between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD' between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nAllele frequencies\nall\t", for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars().alleleFreq[d][1]), for sp in range(numSubPop): print >> output, "\n%d\t" % sp, for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars(sp).alleleFreq[d][1]), print >> output, "\n", # hetero frequency AvgHetero = 0 for d in range(pop.totNumLoci()): AvgHetero += pop.dvars().heteroFreq[d][0] AvgHetero /= pop.totNumLoci() # save to pop pop.dvars().AvgHetero = AvgHetero # output it print >> output, '\nAverage counted heterozygosity is %.4f.\n' % AvgHetero return True
|
i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)]
|
if noDSLChrom > -1: i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] else: noDSLLD = []
|
def outputStatistics(pop, args): ''' this function will be working with a pyOperator to output statistics. Many parameters will be passed, packed as a tuple. We need to output 1. LD (D') from a central marker to all others on a non-DSL chromosome, at burnin and before and after migration 2. LD (D') from a central DSL to all others, at burnin and end 3. Fst before and after migration 4. allele frequency at DSL 5. Mean observed heterogeneity at the marker loci ''' # unwrap parameter (burnin, split, mixing, endGen, outfile) = args # gen = pop.gen() # see how long the simulation has been running if gen == burnin: print "Start introducing disease\t\t" elif gen == split: print "Start no-migration stage\t\t" elif gen == mixing: print "Start mixing\t\t" elif gen == endGen: print "End of simulation. \n" # #### preparations # number of loci when not counting DSL numLoci = pop.dvars().numLoci # non DSL loci, for convenience nonDSL = range( pop.totNumLoci() ) DSL = pop.dvars().DSL for loc in DSL: nonDSL.remove(loc) # In this analysis, we also need to know # 1. a DSL that is closest to the center of a chromosome toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL] ctrChromDSL = DSL[ [x==min(toCtrDist) for x in toCtrDist].index(True)] ctrChrom = pop.chromLocusPair(ctrChromDSL)[0] # 2. first chromosome without DSL noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) # # loci pairs on the selected chromosomes when calculating LD i = pop.chromBegin( ctrChrom) ctrDSLLD = [ [x, ctrChromDSL] for x in range(i, ctrChromDSL)] + \ [ [ctrChromDSL, x] for x in range(ctrChromDSL+1, i+numLoci+1)] i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] # save these info for later use (a plotting function will # use these info. pop.dvars().ctrChrom = ctrChrom pop.dvars().ctrChromDSL = ctrChromDSL pop.dvars().ctrDSLLD = ctrDSLLD pop.dvars().noDSLChrom = noDSLChrom pop.dvars().noDSLLD = noDSLLD # #@@@ NOW, output statistics # append to output file. output = open(outfile, 'a') # first, calculate LD and other statistics Stat(pop, alleleFreq=DSL, LD = ctrDSLLD + noDSLLD, Fst = nonDSL, heteroFreq = range( pop.totNumLoci() ) ) # output D', allele frequency at split, mixing and endGen if gen in [split, mixing, endGen]: print >> output, "Average Fst estimated from non-DSL at gen %d: %.4f \n" % (gen, pop.dvars().AvgFst) print >> output, "D between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD' between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nAllele frequencies\nall\t", for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars().alleleFreq[d][1]), for sp in range(numSubPop): print >> output, "\n%d\t" % sp, for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars(sp).alleleFreq[d][1]), print >> output, "\n", # hetero frequency AvgHetero = 0 for d in range(pop.totNumLoci()): AvgHetero += pop.dvars().heteroFreq[d][0] AvgHetero /= pop.totNumLoci() # save to pop pop.dvars().AvgHetero = AvgHetero # output it print >> output, '\nAverage counted heterozygosity is %.4f.\n' % AvgHetero return True
|
print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]],
|
if noDSLChrom > -1 : print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]],
|
def outputStatistics(pop, args): ''' this function will be working with a pyOperator to output statistics. Many parameters will be passed, packed as a tuple. We need to output 1. LD (D') from a central marker to all others on a non-DSL chromosome, at burnin and before and after migration 2. LD (D') from a central DSL to all others, at burnin and end 3. Fst before and after migration 4. allele frequency at DSL 5. Mean observed heterogeneity at the marker loci ''' # unwrap parameter (burnin, split, mixing, endGen, outfile) = args # gen = pop.gen() # see how long the simulation has been running if gen == burnin: print "Start introducing disease\t\t" elif gen == split: print "Start no-migration stage\t\t" elif gen == mixing: print "Start mixing\t\t" elif gen == endGen: print "End of simulation. \n" # #### preparations # number of loci when not counting DSL numLoci = pop.dvars().numLoci # non DSL loci, for convenience nonDSL = range( pop.totNumLoci() ) DSL = pop.dvars().DSL for loc in DSL: nonDSL.remove(loc) # In this analysis, we also need to know # 1. a DSL that is closest to the center of a chromosome toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL] ctrChromDSL = DSL[ [x==min(toCtrDist) for x in toCtrDist].index(True)] ctrChrom = pop.chromLocusPair(ctrChromDSL)[0] # 2. first chromosome without DSL noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) # # loci pairs on the selected chromosomes when calculating LD i = pop.chromBegin( ctrChrom) ctrDSLLD = [ [x, ctrChromDSL] for x in range(i, ctrChromDSL)] + \ [ [ctrChromDSL, x] for x in range(ctrChromDSL+1, i+numLoci+1)] i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] # save these info for later use (a plotting function will # use these info. pop.dvars().ctrChrom = ctrChrom pop.dvars().ctrChromDSL = ctrChromDSL pop.dvars().ctrDSLLD = ctrDSLLD pop.dvars().noDSLChrom = noDSLChrom pop.dvars().noDSLLD = noDSLLD # #@@@ NOW, output statistics # append to output file. output = open(outfile, 'a') # first, calculate LD and other statistics Stat(pop, alleleFreq=DSL, LD = ctrDSLLD + noDSLLD, Fst = nonDSL, heteroFreq = range( pop.totNumLoci() ) ) # output D', allele frequency at split, mixing and endGen if gen in [split, mixing, endGen]: print >> output, "Average Fst estimated from non-DSL at gen %d: %.4f \n" % (gen, pop.dvars().AvgFst) print >> output, "D between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD' between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nAllele frequencies\nall\t", for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars().alleleFreq[d][1]), for sp in range(numSubPop): print >> output, "\n%d\t" % sp, for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars(sp).alleleFreq[d][1]), print >> output, "\n", # hetero frequency AvgHetero = 0 for d in range(pop.totNumLoci()): AvgHetero += pop.dvars().heteroFreq[d][0] AvgHetero /= pop.totNumLoci() # save to pop pop.dvars().AvgHetero = AvgHetero # output it print >> output, '\nAverage counted heterozygosity is %.4f.\n' % AvgHetero return True
|
print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]],
|
if noDSLChrom > -1: print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]],
|
def outputStatistics(pop, args): ''' this function will be working with a pyOperator to output statistics. Many parameters will be passed, packed as a tuple. We need to output 1. LD (D') from a central marker to all others on a non-DSL chromosome, at burnin and before and after migration 2. LD (D') from a central DSL to all others, at burnin and end 3. Fst before and after migration 4. allele frequency at DSL 5. Mean observed heterogeneity at the marker loci ''' # unwrap parameter (burnin, split, mixing, endGen, outfile) = args # gen = pop.gen() # see how long the simulation has been running if gen == burnin: print "Start introducing disease\t\t" elif gen == split: print "Start no-migration stage\t\t" elif gen == mixing: print "Start mixing\t\t" elif gen == endGen: print "End of simulation. \n" # #### preparations # number of loci when not counting DSL numLoci = pop.dvars().numLoci # non DSL loci, for convenience nonDSL = range( pop.totNumLoci() ) DSL = pop.dvars().DSL for loc in DSL: nonDSL.remove(loc) # In this analysis, we also need to know # 1. a DSL that is closest to the center of a chromosome toCtrDist = [abs(pop.locusDist(x)-numLoci/2) for x in DSL] ctrChromDSL = DSL[ [x==min(toCtrDist) for x in toCtrDist].index(True)] ctrChrom = pop.chromLocusPair(ctrChromDSL)[0] # 2. first chromosome without DSL noDSLChrom = [pop.numLoci(x)==numLoci for x in range(pop.numChrom())].index(True) # # loci pairs on the selected chromosomes when calculating LD i = pop.chromBegin( ctrChrom) ctrDSLLD = [ [x, ctrChromDSL] for x in range(i, ctrChromDSL)] + \ [ [ctrChromDSL, x] for x in range(ctrChromDSL+1, i+numLoci+1)] i = pop.chromBegin( noDSLChrom) noDSLLD = [ [i+x, i+numLoci/2] for x in range(numLoci/2)] + \ [ [i + numLoci/2, i+x] for x in range(numLoci/2+1, numLoci)] # save these info for later use (a plotting function will # use these info. pop.dvars().ctrChrom = ctrChrom pop.dvars().ctrChromDSL = ctrChromDSL pop.dvars().ctrDSLLD = ctrDSLLD pop.dvars().noDSLChrom = noDSLChrom pop.dvars().noDSLLD = noDSLLD # #@@@ NOW, output statistics # append to output file. output = open(outfile, 'a') # first, calculate LD and other statistics Stat(pop, alleleFreq=DSL, LD = ctrDSLLD + noDSLLD, Fst = nonDSL, heteroFreq = range( pop.totNumLoci() ) ) # output D', allele frequency at split, mixing and endGen if gen in [split, mixing, endGen]: print >> output, "Average Fst estimated from non-DSL at gen %d: %.4f \n" % (gen, pop.dvars().AvgFst) print >> output, "D between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD[ld[0]][ld[1]], print >> output, "\n\nD' between DSL %d (chrom %d) and surrounding markers at gen %d" \ % (ctrChromDSL, ctrChrom, gen) for ld in ctrDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nD' between a center marker %d (chrom %d) and surrounding markers at gen %d" \ % (pop.chromBegin(noDSLChrom)+numLoci/2, noDSLChrom, gen) for ld in noDSLLD: print >> output, '%.4f ' % pop.dvars().LD_prime[ld[0]][ld[1]], print >> output, "\n\nAllele frequencies\nall\t", for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars().alleleFreq[d][1]), for sp in range(numSubPop): print >> output, "\n%d\t" % sp, for d in DSL: print >> output, '%.4f ' % (1. - pop.dvars(sp).alleleFreq[d][1]), print >> output, "\n", # hetero frequency AvgHetero = 0 for d in range(pop.totNumLoci()): AvgHetero += pop.dvars().heteroFreq[d][0] AvgHetero /= pop.totNumLoci() # save to pop pop.dvars().AvgHetero = AvgHetero # output it print >> output, '\nAverage counted heterozygosity is %.4f.\n' % AvgHetero return True
|
for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off()
|
if pop.dvars().noDSLChrom > -1: for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() else: res['DpNon'] = 0 res['DNon'] = 0 if hasRPy: r.plot( 0, 0, main="There is no chromosome without DSL", xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.dev_off()
|
def plotLD(pop, epsFile, jpgFile): ''' plot LD values in R and convert to jpg if possible ''' # return max LD res = {} # dist: distance (location) of marker # ldprime: D' value dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().ctrDSLLD: if ld[1] == pop.dvars().ctrChromDSL: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpDSL'] = max(ldprime) res['DDSL'] = max(ldvalue) if hasRPy: r.postscript(file=epsFile) r.par(mfrow=[2,1]) r.plot( dist, ldprime, main="D' between DSL and other markers on chrom %d" % (pop.dvars().ctrChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.dvars().ctrChromDSL), lty=3 ) r.axis( 1, [pop.locusDist(pop.dvars().ctrChromDSL)], ['DSL']) dist = [] ldprime = [] # D' ldvalue = [] # D for ld in pop.dvars().noDSLLD: if ld[1] == pop.chromBegin(pop.dvars().noDSLChrom) + numLoci/2: dist.append(pop.locusDist(ld[0])) else: dist.append(pop.locusDist(ld[1])) ldprime.append(pop.dvars().LD_prime[ld[0]][ld[1]]) ldvalue.append(pop.dvars().LD[ld[0]][ld[1]]) res['DpNon'] = max(ldprime) res['DNon'] = max(ldvalue) if hasRPy: r.plot( dist, ldprime, main="D' between marker %d and other markers on chrom %d" \ % (numLoci/2+1, pop.dvars().noDSLChrom+1), xlab="marker location", ylab="D'", type='b', ylim=[0,1]) r.abline( v = pop.locusDist(pop.chromBegin(pop.dvars().noDSLChrom)+pop.dvars().numLoci/2), lty=3 ) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
def TDT(DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def TDT(geneHunter, DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def TDT(DSL, cutoff, dataDir, data, epsFile, jpgFile): ''' use TDT method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying TDT method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghTDT.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("tdt " + inputfile + ".ped\n") f.close() # run gene hunter os.system(geneHunter + " < ghTDT.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value scan = re.compile('loc(\d+)\s+- Allele \d+\s+\d+\s+\d+\s+[\d.]+\s+([\d.]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("res.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match continue res.close() except: print "Can not open result file. TDT failed" return (0,[]) # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('ghTDT.cmd') except: pass # now, we need to see how TDT works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False, ylim=[0.01, 5]) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = cutoff ) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
if not hasRPy:
|
if not hasRPy or geneHunter in ['', 'none']:
|
def TDT(DSL, cutoff, dataDir, data, epsFile, jpgFile): ''' use TDT method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying TDT method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghTDT.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("tdt " + inputfile + ".ped\n") f.close() # run gene hunter os.system(geneHunter + " < ghTDT.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value scan = re.compile('loc(\d+)\s+- Allele \d+\s+\d+\s+\d+\s+[\d.]+\s+([\d.]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("res.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match continue res.close() except: print "Can not open result file. TDT failed" return (0,[]) # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('ghTDT.cmd') except: pass # now, we need to see how TDT works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (TDT)", xlab="chromosome", ylab="-log10 p-value", type='l', axes=False, ylim=[0.01, 5]) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = cutoff ) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
def Linkage(DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def Linkage(geneHunter, DSL, cutoff, dataDir, data, epsFile, jpgFile):
|
def Linkage(DSL, cutoff, dataDir, data, epsFile, jpgFile): ''' use Linkage method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying Linkage (LOD) method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghLOD.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("single point on\n") f.write("scan pedigrees " + inputfile + ".ped\n") f.write("photo tmp.txt\n") f.write("total stat\n") f.write("q\n") f.close() # run gene hunter os.system(geneHunter + " < ghLOD.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value # position (locxx) -- Lodscore -- NPL score -- p-value -- information scan = re.compile('loc(\d+)\s+[^\s]+\s+[^\s]+\s+([^\s]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("tmp.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match #print l #print err continue res.close() except Exception, err: print type(err), err print "Can not open result file tmp.txt. LOD failed" return (0,[]) # did not get anything if minPvalue == [1]*(numLoci-1): print "Do not get any p-value, something is wrong" # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('tmp.txt') os.unlink('ghLOD.cmd') except: pass # now, we need to see how Linkage works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (LOD)", ylim=[0.01,5], xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = cutoff ) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
if not hasRPy:
|
if not hasRPy or geneHunter in ['', 'none']:
|
def Linkage(DSL, cutoff, dataDir, data, epsFile, jpgFile): ''' use Linkage method to analyze the results. Has to have rpy installed ''' if not hasRPy: return (0,[]) # write a batch file and call gh allPvalue = [] print "Applying Linkage (LOD) method to affected sibpairs " for ch in range(numChrom): inputfile = dataDir+data+ "_%d" % ch if not os.path.isfile(inputfile + ".ped"): print "Ped file ", inputfile+".ped does not exist. Can not apply TDT method." return (0,[]) # batch file f=open("ghLOD.cmd","w") f.write("load markers " + inputfile + ".dat\n") f.write("single point on\n") f.write("scan pedigrees " + inputfile + ".ped\n") f.write("photo tmp.txt\n") f.write("total stat\n") f.write("q\n") f.close() # run gene hunter os.system(geneHunter + " < ghLOD.cmd > res.txt ") # get the result # ( I was using # | grep '^loc' | tr -d 'a-zA-Z+-' > " + outputfile) # but this is not portable # # use re package # get only loc number and p-value # position (locxx) -- Lodscore -- NPL score -- p-value -- information scan = re.compile('loc(\d+)\s+[^\s]+\s+[^\s]+\s+([^\s]+)\s*.*') minPvalue = [1]*(numLoci-1) try: res = open("tmp.txt") # read result for l in res.readlines(): try: # get minimal p-value for all alleles at each locus (loc,pvalue) = scan.match(l).groups() if minPvalue[int(loc)-1] > float(pvalue): minPvalue[int(loc)-1] = float(pvalue) except: # does not match #print l #print err continue res.close() except Exception, err: print type(err), err print "Can not open result file tmp.txt. LOD failed" return (0,[]) # did not get anything if minPvalue == [1]*(numLoci-1): print "Do not get any p-value, something is wrong" # collect -log10 pvalue allPvalue.extend([-math.log10(max(x,1e-6)) for x in minPvalue]) # There will be numLoci-1 numbers, pad to the correct length allPvalue.append(0) try: os.unlink('res.txt') os.unlink('tmp.txt') os.unlink('ghLOD.cmd') except: pass # now, we need to see how Linkage works with a set of p-values around DSL # DSL is global res = [] for d in DSL: res.append( max(allPvalue[(d-2):(d+2)])) # use R to draw a picture r.postscript(file=epsFile) r.plot(allPvalue, main="-log10(P-value) for each marker (LOD)", ylim=[0.01,5], xlab="chromosome", ylab="-log10 p-value", type='l', axes=False) r.box() r.abline( v = [DSLafter[g]+DSLdist[g] for g in range(len(DSL))], lty=3) r.abline( h = cutoff ) r.axis(1, [numLoci*x for x in range(numChrom)], [str(x+1) for x in range(numChrom)]) r.axis(2) r.dev_off() # try to get a jpg file try: if os.system("convert -rotate 90 %s %s " % (epsFile, jpgFile) ) == 0: return (2,res) # success else: return (1,res) # fail except: return (1,res) # fail
|
mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx):
|
mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, geneHunter, dryrun, popIdx):
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or Linkage method 6. return a text summary and a result dictionary ''' # get population result = {'id':popIdx, 'mu':mu, 'mi':mi, 'rec':rec} logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) # check if the population is using the same parameters as requested if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) # note that this file does not have affectedness info. SavePopulation(pop, popFile) # log file is ... summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # save Fst, Het in res result['Fst'] = pop.dvars().AvgFst result['AvgHet'] = pop.dvars().AvgHetero result['alleleFreq'] = [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL] # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # ldres has max D' on a chrom with DSL, and a chrom without DSL (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result['DpDSL'] = ldres['DpDSL'] result['DpNon'] = ldres['DpNon'] result['DDSL'] = ldres['DDSL'] result['DNon'] = ldres['DNon'] # # apply penetrance and get numSample for each sample summary += "<h3>Samples using different penetrance function</h3>\n" # now, deal with each penetrance ... for p in range(len(peneFunc)): if peneFunc[p].find('recessive') == 0: # start with receissive print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p]), numSample) elif peneFunc[p].find('additive') == 0: # start with additive print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p]), numSample) elif peneFunc[p].find('custom') == 0: # start with custom print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p]), numSample) # calculate population statistics like prevalence result.update( popStat(pop, peneFunc[p]) ) # for each sample for sn in range(numSample): print "Processing sample %s%d" % ( peneFunc[p], sn) # save these samples penDir = dataDir + "/" + peneFunc[p] + str(sn) relDir = 'pop_%d/%s%d/' % (popIdx, peneFunc[p], sn) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[sn][0] != None: summary += str(s[sn][0].popSize()) + " (case-control), " if s[sn][1] != None: summary += str(s[sn][1].popSize()) + " (affected sibs), " if s[sn][2] != None: summary += str(s[sn][2].popSize()) + " (unaffected sibs) " summary += '<ul>' # write samples to different format if 'simuPOP' in saveFormat: print "Write to simuPOP binary format" summary += '<li>simuPOP binary format:' if s[sn][0] != None: # has case control binFile = penDir + "/caseControl.bin" s[sn][0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[sn][1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[sn][1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[sn][2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[sn][2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: print "Write to linkage format" summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) # here we are facing a problem of using which allele frequency for the sample # In reality, if it is difficult to estimate population allele frequency, # sample frequency has to be used. Otherwise, population frequency should # be used whenever possible. Here, we use population allele frequency, with only # one problem in that we need to remove frequencies at DSL (since samples do not # have DSL). af = [] Stat(pop, alleleFreq=range(pop.totNumLoci())) for x in range( pop.totNumLoci() ): if x not in pop.dvars().DSL: af.append( pop.dvars().alleleFreq[x] ) if s[sn][1] != None: # has case control for ch in range(0, pop.numChrom() ): SaveLinkage(pop=s[sn][1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[sn][2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[sn][2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['TDT_%s_%d' % (peneFunc[p], sn)] = res # then the Linkage method (suc,res) = Linkage(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>LOD analysis for affected sibpair data: <a href="%s/LOD.eps">LOD.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/LOD.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['LOD_%s_%d' % (peneFunc[p], sn)] = res return (summary, result)
|
(suc,res) = TDT(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()),
|
(suc,res) = TDT(geneHunter, pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()),
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or Linkage method 6. return a text summary and a result dictionary ''' # get population result = {'id':popIdx, 'mu':mu, 'mi':mi, 'rec':rec} logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) # check if the population is using the same parameters as requested if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) # note that this file does not have affectedness info. SavePopulation(pop, popFile) # log file is ... summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # save Fst, Het in res result['Fst'] = pop.dvars().AvgFst result['AvgHet'] = pop.dvars().AvgHetero result['alleleFreq'] = [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL] # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # ldres has max D' on a chrom with DSL, and a chrom without DSL (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result['DpDSL'] = ldres['DpDSL'] result['DpNon'] = ldres['DpNon'] result['DDSL'] = ldres['DDSL'] result['DNon'] = ldres['DNon'] # # apply penetrance and get numSample for each sample summary += "<h3>Samples using different penetrance function</h3>\n" # now, deal with each penetrance ... for p in range(len(peneFunc)): if peneFunc[p].find('recessive') == 0: # start with receissive print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p]), numSample) elif peneFunc[p].find('additive') == 0: # start with additive print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p]), numSample) elif peneFunc[p].find('custom') == 0: # start with custom print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p]), numSample) # calculate population statistics like prevalence result.update( popStat(pop, peneFunc[p]) ) # for each sample for sn in range(numSample): print "Processing sample %s%d" % ( peneFunc[p], sn) # save these samples penDir = dataDir + "/" + peneFunc[p] + str(sn) relDir = 'pop_%d/%s%d/' % (popIdx, peneFunc[p], sn) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[sn][0] != None: summary += str(s[sn][0].popSize()) + " (case-control), " if s[sn][1] != None: summary += str(s[sn][1].popSize()) + " (affected sibs), " if s[sn][2] != None: summary += str(s[sn][2].popSize()) + " (unaffected sibs) " summary += '<ul>' # write samples to different format if 'simuPOP' in saveFormat: print "Write to simuPOP binary format" summary += '<li>simuPOP binary format:' if s[sn][0] != None: # has case control binFile = penDir + "/caseControl.bin" s[sn][0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[sn][1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[sn][1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[sn][2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[sn][2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: print "Write to linkage format" summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) # here we are facing a problem of using which allele frequency for the sample # In reality, if it is difficult to estimate population allele frequency, # sample frequency has to be used. Otherwise, population frequency should # be used whenever possible. Here, we use population allele frequency, with only # one problem in that we need to remove frequencies at DSL (since samples do not # have DSL). af = [] Stat(pop, alleleFreq=range(pop.totNumLoci())) for x in range( pop.totNumLoci() ): if x not in pop.dvars().DSL: af.append( pop.dvars().alleleFreq[x] ) if s[sn][1] != None: # has case control for ch in range(0, pop.numChrom() ): SaveLinkage(pop=s[sn][1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[sn][2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[sn][2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['TDT_%s_%d' % (peneFunc[p], sn)] = res # then the Linkage method (suc,res) = Linkage(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>LOD analysis for affected sibpair data: <a href="%s/LOD.eps">LOD.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/LOD.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['LOD_%s_%d' % (peneFunc[p], sn)] = res return (summary, result)
|
(suc,res) = Linkage(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()),
|
(suc,res) = Linkage(geneHunter, pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()),
|
def processOnePopulation(dataDir, numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, peneFunc, penePara, N, numSample, dryrun, popIdx): ''' this function organize all previous functions and 1. generate (or load) a population 2. apply different kinds of penetrance functions 3. draw sample 4. save samples 5. apply TDT and/or Linkage method 6. return a text summary and a result dictionary ''' # get population result = {'id':popIdx, 'mu':mu, 'mi':mi, 'rec':rec} logFile = dataDir + "/pop_" + str(popIdx) + ".log" popFile = dataDir + "/pop_" + str(popIdx) + ".bin" genDataset = True if os.path.isfile(popFile) and (not overwrite): print "Loading a pre-existing file ", popFile pop = LoadPopulation(popFile) # check if the population is using the same parameters as requested if abs(pop.dvars().mutationRate - mu) + abs(pop.dvars().migrationRate - mi) \ + abs( pop.dvars().recombinationRate - rec) < 1e-7: genDataset = False print "Dataset already exists, load it directly. (use --overwrite True to change this behavior)" else: print "A dataset is present but was generated with different parameters. Re-generating." if genDataset: print "Generating dataset ", str(popIdx) pop = simuComplexDisease( numChrom, numLoci, markerType, DSLafter, DSLdist, initSize, meanInitAllele, burnin, introGen, minAlleleFreq, maxAlleleFreq, fitness, mlSelModel, numSubPop, finalSize, noMigrGen, mixingGen, popSizeFunc, migrModel, mu, mi, rec, dryrun, logFile) # note that this file does not have affectedness info. SavePopulation(pop, popFile) # log file is ... summary = '''\ <h2><a name="pop_%d">Dataset %d</a></h2> <h3>Log file (LD and other statistics): <a href="pop_%d/pop_%d.log">pop_%d.log</a></h3> ''' % (popIdx, popIdx, popIdx, popIdx, popIdx) # # actually write the log file in the summary page try: lf = open(logFile) summary += "<pre>\n"+lf.read()+"\n</pre>\n" lf.close() except: print "Can not open log file, ignoring. " # # save Fst, Het in res result['Fst'] = pop.dvars().AvgFst result['AvgHet'] = pop.dvars().AvgHetero result['alleleFreq'] = [1- pop.dvars().alleleFreq[i][1] for i in pop.dvars().DSL] # # plot LD, res = 0, fail, 1: eps file, 2: converted to jpg epsFile = dataDir + "/LD_" + str(popIdx) + ".eps" jpgFile = dataDir + "/LD_" + str(popIdx) + ".jpg" # ldres has max D' on a chrom with DSL, and a chrom without DSL (suc,ldres) = plotLD(pop, epsFile, jpgFile) if suc > 0 : # eps file successfully generated summary += """<p>D' measures on two chromosomes with/without DSL at the last gen: <a href="pop_%d/LD_%d.eps">LD.eps</a></p>\n""" % (popIdx, popIdx) if suc > 1 : # jpg file is generated summary += '''<img src="pop_%d/LD_%d.jpg" width=800, height=600>''' % (popIdx, popIdx) result['DpDSL'] = ldres['DpDSL'] result['DpNon'] = ldres['DpNon'] result['DDSL'] = ldres['DDSL'] result['DNon'] = ldres['DNon'] # # apply penetrance and get numSample for each sample summary += "<h3>Samples using different penetrance function</h3>\n" # now, deal with each penetrance ... for p in range(len(peneFunc)): if peneFunc[p].find('recessive') == 0: # start with receissive print "Using recessive penetrance function" summary += "<h4>Recessive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, recessive( penePara[p]), numSample) elif peneFunc[p].find('additive') == 0: # start with additive print "Using additive penetrance function" summary += "<h4>Additive single-locus, heterogeneity multi-locus</h4>\n" s = drawSamples(pop, additive(penePara[p]), numSample) elif peneFunc[p].find('custom') == 0: # start with custom print "Using customized penetrance function" summary += "<h4>Customized penetrance function</h4>\n" s = drawSamples(pop, customPene(penePara[p]), numSample) # calculate population statistics like prevalence result.update( popStat(pop, peneFunc[p]) ) # for each sample for sn in range(numSample): print "Processing sample %s%d" % ( peneFunc[p], sn) # save these samples penDir = dataDir + "/" + peneFunc[p] + str(sn) relDir = 'pop_%d/%s%d/' % (popIdx, peneFunc[p], sn) _mkdir(penDir) summary += "<p>Case-control, affected and unaffected sibpairs saved in different formats. Sample sizes are " if s[sn][0] != None: summary += str(s[sn][0].popSize()) + " (case-control), " if s[sn][1] != None: summary += str(s[sn][1].popSize()) + " (affected sibs), " if s[sn][2] != None: summary += str(s[sn][2].popSize()) + " (unaffected sibs) " summary += '<ul>' # write samples to different format if 'simuPOP' in saveFormat: print "Write to simuPOP binary format" summary += '<li>simuPOP binary format:' if s[sn][0] != None: # has case control binFile = penDir + "/caseControl.bin" s[sn][0].savePopulation(binFile) summary += '<a href="%scaseControl.bin"> caseControl.bin</a>, ' % relDir if s[sn][1] != None: # has affected sibpairs binFile = penDir + "/affectedSibpairs.bin" s[sn][1].savePopulation(binFile) summary += '<a href="%saffectedSibpairs.bin"> affectedSibpairs.bin</a>, ' % relDir if s[sn][2] != None: binFile = penDir + "/unaffectedSibpairs.bin" s[sn][2].savePopulation(binFile) summary += '<a href="%sunaffectedSibpairs.bin"> unaffectedSibpirs.bin</a>, ' % relDir summary += '</li>\n' if 'Linkage' in saveFormat: print "Write to linkage format" summary += '<li>Linkage format by chromosome:' linDir = penDir + "/Linkage/" _mkdir(linDir) # here we are facing a problem of using which allele frequency for the sample # In reality, if it is difficult to estimate population allele frequency, # sample frequency has to be used. Otherwise, population frequency should # be used whenever possible. Here, we use population allele frequency, with only # one problem in that we need to remove frequencies at DSL (since samples do not # have DSL). af = [] Stat(pop, alleleFreq=range(pop.totNumLoci())) for x in range( pop.totNumLoci() ): if x not in pop.dvars().DSL: af.append( pop.dvars().alleleFreq[x] ) if s[sn][1] != None: # has case control for ch in range(0, pop.numChrom() ): SaveLinkage(pop=s[sn][1], popType='sibpair', output = linDir+"/Aff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">affected</a>, ' % relDir if s[sn][2] != None: for ch in range(0,pop.numChrom() ): SaveLinkage(pop=s[sn][2], popType='sibpair', output = linDir+"/Unaff_%d" % ch, chrom=ch, recombination=pop.dvars().recombinationRate, alleleFreq=af, daf=0.1) summary += '<a href="%sLinkage">unaffected</a>' % relDir summary += '</li>\n' summary += '</ul>\n' # if there is a valid gene hunter program, run it (suc,res) = TDT(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/TDT.eps", penDir + "/TDT.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>TDT analysis for affected sibpair data: <a href="%s/TDT.eps">TDT.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/TDT.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['TDT_%s_%d' % (peneFunc[p], sn)] = res # then the Linkage method (suc,res) = Linkage(pop.dvars().DSL, -math.log10(0.05/pop.totNumLoci()), penDir, "/Linkage/Aff", penDir + "/LOD.eps", penDir + "/LOD.jpg") # if suc > 0 : # eps file succe if suc > 0 : # eps file successfully generated summary += """<h4>LOD analysis for affected sibpair data: <a href="%s/LOD.eps">LOD.eps</a>""" % relDir if suc > 1 : # jpg file is generated summary += '''<p><img src="%s/LOD.jpg" width=800, height=600></p>''' % relDir # keep some numbers depending on the penetrance model result['LOD_%s_%d' % (peneFunc[p], sn)] = res return (summary, result)
|
dryrun, popIdx)
|
geneHunter, dryrun, popIdx)
|
def writeReport(content, allParam, numChrom, numLoci, DSLafter, peneFunc, numSample, results): ''' write a HTML file. The parts for each population has been written but we need a summary table. ''' print "Writing a report (saved in summary.htm )" try: summary = open(outputDir + "/summary.htm", 'w') except: raise exceptions.IOError("Can not open a summary file : " + outputDir + "/summary.htm to write") summary.write(''' <HTML> <HEAD> <TITLE>Summary of simulations</TITLE> <META NAME="description" CONTENT="summary of simulation"> <META NAME="keywords" CONTENT="simuPOP"> <META NAME="resource-type" CONTENT="document"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY > <h1>Output of %s</h1> <p><b>Time of simulation: </b> %s </p> <h2>Parameters </h2> <ul>''' % (sys.argv[0], time.asctime()) ) # write out parameters # start from options[1] for i in range(1, len(options)-1): # check type if options[i].has_key('configName'): if type( allParam[i-1]) in [types.TupleType, types.ListType]: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], ', '.join( map(str, allParam[i-1])))) else: summary.write('''<li><b>%s:</b> %s</li>\n''' % \ (options[i]['configName'], str(allParam[i-1]))) # a table built from res which has # idx, muta, migr, rec, af?, Fst, Het, TDT? summary.write(''' </ul> <h2>Summary of datasets </h2> <p>The following table lists population id, mutation rate, migration rate, recombination rate, Fst, average heterozygosity, highest D'/D between a DSL and all surrounding markers (not necessarily its cloest marker), highest D'/D between a marker with its surrounding markers on a chromsome without DSL, allele frequency at DSL, -log10 p-values (TDT method and Linkage method, + for exceeds and - for less than cutoff value -log10(pvalue/total number of loci) ) at all relevant DSL. The cutoff is chosen as -log10(0.05/number of loci) which is the Bonferroni correction. Other statistics include K (population prevalence), Ks (sibling recurrance risk), Ls=Ks/K (lambda_s, sibling recurrance ratio), P11 (P(NN | affected)), P12 (P(NS | affected)), P13 (P(SS|affected)), F' = P(disease allele | affected) = allele frequency among affected individuals.</p> <table border="1"> <tr><th>id </th> <th>mu</th> <th>mi</th> <th>rec</th> <th>Fst</th> <th>Het</th> <th>D'(dsl)</th> <th>D (dsl)</th> <th>D'(non)</th> <th>D (non)</th> ''') for i in range(len(DSLafter)): summary.write('<th>allele Frq%d</th>'%(i+1)) # # has TDT and some penetrance function if len(peneFunc) > 0: summary.write('<th>K</th><th>Ks</th><th>Ks/K</th>') summary.write('<th>P11</th><th>P12</th><th>P22</th>') summary.write("<th>F'</th>") for p in peneFunc: for met in ['TDT', 'LOD']: for num in range(numSample): # samples summary.write('<th>%s:%s-%d</th>'%(p,met,num)) summary.write('</tr>') # # end of headers, now result for res in results: summary.write('''<tr><td><a href="#pop_%d">%d</a></td> ''' \ % (res['id'], res['id'])) summary.write('<td>%.5g</td>' % res['mu']) summary.write('<td>%.5g</td>' % res['mi']) summary.write('<td>%.5g</td>' % res['rec']) summary.write('<td>%.3g</td>' % res['Fst']) summary.write('<td>%.3g</td>' % res['AvgHet']) summary.write('<td>%.3g</td>' % res['DpDSL']) summary.write('<td>%.3g</td>' % res['DDSL']) summary.write('<td>%.3g</td>' % res['DpNon']) summary.write('<td>%.3g</td>' % res['DNon']) for i in range(len(DSLafter)): summary.write('<td>%.3f</td>'% res['alleleFreq'][i] ) # for each penetrance function if len(peneFunc) > 0: for p in peneFunc: # penetrance function summary.write('<td>%.3g</td>' % res[p+'_K']) summary.write('<td>%.3g</td>' % res[p+'_Ks']) summary.write('<td>%.3g</td>' % res[p+'_Ls']) summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P11'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P12'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_P22'] ]) + '</td>') summary.write('<td>' + ','.join( ['%.3g'%x for x in res[p+'_Fprime'] ]) + '</td>') for met in ['TDT', 'LOD']: for num in range(numSample): # samples plusMinus = '' for pvalue in res[met+'_'+p+'_'+str(num)]: if pvalue > -math.log10(0.05/(numChrom*numLoci)): plusMinus += '+' else: plusMinus += '-' summary.write('<td>'+plusMinus+'</td>') summary.write('''</tr>''') # the middle (big) and last piece) summary.write('''</table> %s <h2>Usage of %s</h2> <pre>%s </pre> </BODY></HTML> ''' % ( content, sys.argv[0], simuOpt.usage(options, __doc__))) summary.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.