Created
June 19, 2015 16:16
-
-
Save pjbriggs/a76cffef31e0dd1babad to your computer and use it in GitHub Desktop.
Python script that converts a bedGraph format file to a wig file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Convert bedgraph file into wig format | |
# | |
# Based on perl script by Dave Tang | |
# http://davetang.org/wiki/tiki-index.php?page=wig | |
import optparse | |
import os | |
import gzip | |
if __name__ == "__main__": | |
# Process command line | |
p = optparse.OptionParser(usage="%prog [OPTIONS] BDG [WIG]") | |
p.add_option('-c','--compress',action="store_true",dest="compress",default=False, | |
help="Compress (gzip) the output wig file") | |
p.add_option('-n','--name',action="store",dest="name",default=None, | |
help="Set the 'name' field in the wig file") | |
p.add_option('-d','--description',action="store",dest="desc",default=None, | |
help="Set the 'description' field in the wig file") | |
p.add_option('-s','--step',action="store",dest="step_size",type='int',default=1, | |
help="Set the step size (default is 1)") | |
options,args = p.parse_args() | |
if len(args) != 1: | |
p.error("Need to supply input bdg file name") | |
bdg = args[0] | |
if len(args) == 1: | |
wig = os.path.splitext(os.path.basename(bdg))[0] + '.wig' | |
elif len(args) == 2: | |
wig = args[1] | |
else: | |
p.error("Too many arguments") | |
if options.compress: | |
if not wig.endswith('.gz'): | |
wig += '.gz' | |
fwig = gzip.GzipFile(filename=wig,mode='wb',compresslevel=9) | |
else: | |
fwig = open(wig,'w') | |
if options.name is not None: | |
name = options.name | |
else: | |
name = os.path.basename(bdg) | |
if options.desc is not None: | |
desc = options.desc | |
else: | |
desc = os.path.basename(bdg) | |
step = options.step_size | |
fwig.write("track type=wiggle_0 name=\"%s\" description=\"%s\" visibility=full\n" % | |
(name,desc)) | |
for line in open(bdg,'r'): | |
chrom,start,end = line.strip().split('\t')[:3] | |
data = '\t'.join(line.strip().split('\t')[3:]) | |
fwig.write("fixedStep chrom=%s start=%s step=%d span=1\n" % (chrom,start,step)) | |
for i in xrange(int(start),int(end)+1,step): | |
fwig.write("%s\n" % data) | |
fwig.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment