Skip to content

Instantly share code, notes, and snippets.

@anpefi
Last active January 18, 2016 14:16
Show Gist options
  • Save anpefi/64117115e309815b799a to your computer and use it in GitHub Desktop.
Save anpefi/64117115e309815b799a to your computer and use it in GitHub Desktop.
Script for conversion of datafiles from Genepop to metapop
#! /usr/bin/env python
__author__="Andres Perez-Figueroa"
__date__ ="$14-jan-2016$"
__version_="2.0"
### Conversor from genepop to metapop
### Requires Biopython
### run: python g2m.py
### The program will ask for your datafile in genepop format
### Then will create a metapop file with the extension .mtp
### IF you want to include sex information in the genepop coded as /m or /f at the end of the individual labels
from sys import exit
from Bio.PopGen import GenePop
if __name__ == "__main__":
print "G2M 2.0 - File conversor from Genepop to Metapop"
genepopfile=raw_input('Name of the source file (genepop format): ')
try:
handle = open(genepopfile)
rec = GenePop.read(handle)
handle.close()
except IOError:
print "Can not open file " + genepopfile + " to read. Exiting"
exit(2)
loci=len(rec.loci_list)
pops=len(rec.populations)
print""
metapopfile=genepopfile+".mtp"
try:
f = open(metapopfile, "w")
except IOError:
print "Can not open file " + metapopfile + " to write. Exiting"
exit(2)
f.write("n\t%d\n" % (pops))
f.write("nloci\t%d\n" % (loci))
counter = 1
for p in range(pops):
thisPop=rec.populations[p]
popName=thisPop[0][0].lstrip().split('/')[0]
f.write("%s\n" %(popName))
inds=len(thisPop)
f.write("N\t%d\n"%(inds))
f.write("Ne\t%d\n"%(inds))
f.write("newN\t%d\t%d\n"%(inds/2, inds/2))
for i in range(inds):
name = thisPop[i][0].lstrip()
sex = 0
if name.endswith("/1") or name.endswith("/m"):
sex = 1
name = popName + '_'+ str(i)
f.write("%d\t%s\t%d\t" % (counter, name, sex))
for l in range(loci):
al1=str(thisPop[i][1][l][0]).replace('None','0')
al2=str(thisPop[i][1][l][1]).replace('None','0')
f.write("%s %s\t" % (al1, al2))
f.write("\n")
counter +=1
f.close()
print "Finished!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment