repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
tanghaibao/jcvi | jcvi/variation/snp.py | mappability | def mappability(args):
"""
%prog mappability reference.fasta
Generate 50mer mappability for reference genome. Commands are based on gem
mapper. See instructions:
<https://github.com/xuefzhao/Reference.Mappability>
"""
p = OptionParser(mappability.__doc__)
p.add_option("--mer", default=50, type="int", help="User mer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
ref, = args
K = opts.mer
pf = ref.rsplit(".", 1)[0]
mm = MakeManager()
gem = pf + ".gem"
cmd = "gem-indexer -i {} -o {}".format(ref, pf)
mm.add(ref, gem, cmd)
mer = pf + ".{}mer".format(K)
mapb = mer + ".mappability"
cmd = "gem-mappability -I {} -l {} -o {} -T {}".\
format(gem, K, mer, opts.cpus)
mm.add(gem, mapb, cmd)
wig = mer + ".wig"
cmd = "gem-2-wig -I {} -i {} -o {}".format(gem, mapb, mer)
mm.add(mapb, wig, cmd)
bw = mer + ".bw"
cmd = "wigToBigWig {} {}.sizes {}".format(wig, mer, bw)
mm.add(wig, bw, cmd)
bg = mer + ".bedGraph"
cmd = "bigWigToBedGraph {} {}".format(bw, bg)
mm.add(bw, bg, cmd)
merged = mer + ".filtered-1.merge.bed"
cmd = "python -m jcvi.formats.bed filterbedgraph {} 1".format(bg)
mm.add(bg, merged, cmd)
mm.write() | python | def mappability(args):
"""
%prog mappability reference.fasta
Generate 50mer mappability for reference genome. Commands are based on gem
mapper. See instructions:
<https://github.com/xuefzhao/Reference.Mappability>
"""
p = OptionParser(mappability.__doc__)
p.add_option("--mer", default=50, type="int", help="User mer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
ref, = args
K = opts.mer
pf = ref.rsplit(".", 1)[0]
mm = MakeManager()
gem = pf + ".gem"
cmd = "gem-indexer -i {} -o {}".format(ref, pf)
mm.add(ref, gem, cmd)
mer = pf + ".{}mer".format(K)
mapb = mer + ".mappability"
cmd = "gem-mappability -I {} -l {} -o {} -T {}".\
format(gem, K, mer, opts.cpus)
mm.add(gem, mapb, cmd)
wig = mer + ".wig"
cmd = "gem-2-wig -I {} -i {} -o {}".format(gem, mapb, mer)
mm.add(mapb, wig, cmd)
bw = mer + ".bw"
cmd = "wigToBigWig {} {}.sizes {}".format(wig, mer, bw)
mm.add(wig, bw, cmd)
bg = mer + ".bedGraph"
cmd = "bigWigToBedGraph {} {}".format(bw, bg)
mm.add(bw, bg, cmd)
merged = mer + ".filtered-1.merge.bed"
cmd = "python -m jcvi.formats.bed filterbedgraph {} 1".format(bg)
mm.add(bg, merged, cmd)
mm.write() | [
"def",
"mappability",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mappability",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mer\"",
",",
"default",
"=",
"50",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"User mer size\"",
")",
... | %prog mappability reference.fasta
Generate 50mer mappability for reference genome. Commands are based on gem
mapper. See instructions:
<https://github.com/xuefzhao/Reference.Mappability> | [
"%prog",
"mappability",
"reference",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/snp.py#L34-L81 | train | 200,400 |
tanghaibao/jcvi | jcvi/variation/snp.py | freq | def freq(args):
"""
%prog freq fastafile bamfile
Call SNP frequencies and generate GFF file.
"""
p = OptionParser(freq.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth [default: %default]")
p.add_option("--minqual", default=20, type="int",
help="Minimum quality [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, bamfile = args
cmd = "freebayes -f {0} --pooled-continuous {1}".format(fastafile, bamfile)
cmd += " -F 0 -C {0}".format(opts.mindepth)
cmd += ' | vcffilter -f "QUAL > {0}"'.format(opts.minqual)
cmd += " | vcfkeepinfo - AO RO TYPE"
sh(cmd, outfile=opts.outfile) | python | def freq(args):
"""
%prog freq fastafile bamfile
Call SNP frequencies and generate GFF file.
"""
p = OptionParser(freq.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth [default: %default]")
p.add_option("--minqual", default=20, type="int",
help="Minimum quality [default: %default]")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, bamfile = args
cmd = "freebayes -f {0} --pooled-continuous {1}".format(fastafile, bamfile)
cmd += " -F 0 -C {0}".format(opts.mindepth)
cmd += ' | vcffilter -f "QUAL > {0}"'.format(opts.minqual)
cmd += " | vcfkeepinfo - AO RO TYPE"
sh(cmd, outfile=opts.outfile) | [
"def",
"freq",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"freq",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mindepth\"",
",",
"default",
"=",
"3",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Minimum depth [default: %default]\"... | %prog freq fastafile bamfile
Call SNP frequencies and generate GFF file. | [
"%prog",
"freq",
"fastafile",
"bamfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/snp.py#L279-L301 | train | 200,401 |
tanghaibao/jcvi | jcvi/variation/snp.py | frommaf | def frommaf(args):
"""
%prog frommaf maffile
Convert to four-column tabular format from MAF.
"""
p = OptionParser(frommaf.__doc__)
p.add_option("--validate",
help="Validate coordinates against FASTA [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
maf, = args
snpfile = maf.rsplit(".", 1)[0] + ".vcf"
fp = open(maf)
fw = open(snpfile, "w")
total = 0
id = "."
qual = 20
filter = "PASS"
info = "DP=20"
print("##fileformat=VCFv4.0", file=fw)
print("#CHROM POS ID REF ALT QUAL FILTER INFO".replace(" ", "\t"), file=fw)
for row in fp:
atoms = row.split()
c, pos, ref, alt = atoms[:4]
try:
c = int(c)
except:
continue
c = "chr{0:02d}".format(c)
pos = int(pos)
print("\t".join(str(x) for x in \
(c, pos, id, ref, alt, qual, filter, info)), file=fw)
total += 1
fw.close()
validate = opts.validate
if not validate:
return
from jcvi.utils.cbook import percentage
f = Fasta(validate)
fp = open(snpfile)
nsnps = 0
for row in fp:
if row[0] == '#':
continue
c, pos, id, ref, alt, qual, filter, info = row.split("\t")
pos = int(pos)
feat = dict(chr=c, start=pos, stop=pos)
s = f.sequence(feat)
s = str(s)
assert s == ref, "Validation error: {0} is {1} (expect: {2})".\
format(feat, s, ref)
nsnps += 1
if nsnps % 50000 == 0:
logging.debug("SNPs parsed: {0}".format(percentage(nsnps, total)))
logging.debug("A total of {0} SNPs validated and written to `{1}`.".\
format(nsnps, snpfile)) | python | def frommaf(args):
"""
%prog frommaf maffile
Convert to four-column tabular format from MAF.
"""
p = OptionParser(frommaf.__doc__)
p.add_option("--validate",
help="Validate coordinates against FASTA [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
maf, = args
snpfile = maf.rsplit(".", 1)[0] + ".vcf"
fp = open(maf)
fw = open(snpfile, "w")
total = 0
id = "."
qual = 20
filter = "PASS"
info = "DP=20"
print("##fileformat=VCFv4.0", file=fw)
print("#CHROM POS ID REF ALT QUAL FILTER INFO".replace(" ", "\t"), file=fw)
for row in fp:
atoms = row.split()
c, pos, ref, alt = atoms[:4]
try:
c = int(c)
except:
continue
c = "chr{0:02d}".format(c)
pos = int(pos)
print("\t".join(str(x) for x in \
(c, pos, id, ref, alt, qual, filter, info)), file=fw)
total += 1
fw.close()
validate = opts.validate
if not validate:
return
from jcvi.utils.cbook import percentage
f = Fasta(validate)
fp = open(snpfile)
nsnps = 0
for row in fp:
if row[0] == '#':
continue
c, pos, id, ref, alt, qual, filter, info = row.split("\t")
pos = int(pos)
feat = dict(chr=c, start=pos, stop=pos)
s = f.sequence(feat)
s = str(s)
assert s == ref, "Validation error: {0} is {1} (expect: {2})".\
format(feat, s, ref)
nsnps += 1
if nsnps % 50000 == 0:
logging.debug("SNPs parsed: {0}".format(percentage(nsnps, total)))
logging.debug("A total of {0} SNPs validated and written to `{1}`.".\
format(nsnps, snpfile)) | [
"def",
"frommaf",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"frommaf",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--validate\"",
",",
"help",
"=",
"\"Validate coordinates against FASTA [default: %default]\"",
")",
"opts",
",",
"args",
"=",
... | %prog frommaf maffile
Convert to four-column tabular format from MAF. | [
"%prog",
"frommaf",
"maffile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/snp.py#L304-L367 | train | 200,402 |
tanghaibao/jcvi | jcvi/utils/db.py | libs | def libs(args):
"""
%prog libs libfile
Get list of lib_ids to be run by pull(). The SQL commands:
select library.lib_id, library.name from library join bac on
library.bac_id=bac.id where bac.lib_name="Medicago";
select seq_name from sequence where seq_name like 'MBE%'
and trash is null;
"""
p = OptionParser(libs.__doc__)
p.set_db_opts(dbname="track", credentials=None)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
libfile, = args
sqlcmd = "select library.lib_id, library.name, bac.gb# from library join bac on " + \
"library.bac_id=bac.id where bac.lib_name='Medicago'"
cur = connect(opts.dbname)
results = fetchall(cur, sqlcmd)
fw = open(libfile, "w")
for lib_id, name, gb in results:
name = name.translate(None, "\n")
if not gb:
gb = "None"
print("|".join((lib_id, name, gb)), file=fw)
fw.close() | python | def libs(args):
"""
%prog libs libfile
Get list of lib_ids to be run by pull(). The SQL commands:
select library.lib_id, library.name from library join bac on
library.bac_id=bac.id where bac.lib_name="Medicago";
select seq_name from sequence where seq_name like 'MBE%'
and trash is null;
"""
p = OptionParser(libs.__doc__)
p.set_db_opts(dbname="track", credentials=None)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
libfile, = args
sqlcmd = "select library.lib_id, library.name, bac.gb# from library join bac on " + \
"library.bac_id=bac.id where bac.lib_name='Medicago'"
cur = connect(opts.dbname)
results = fetchall(cur, sqlcmd)
fw = open(libfile, "w")
for lib_id, name, gb in results:
name = name.translate(None, "\n")
if not gb:
gb = "None"
print("|".join((lib_id, name, gb)), file=fw)
fw.close() | [
"def",
"libs",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"libs",
".",
"__doc__",
")",
"p",
".",
"set_db_opts",
"(",
"dbname",
"=",
"\"track\"",
",",
"credentials",
"=",
"None",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
... | %prog libs libfile
Get list of lib_ids to be run by pull(). The SQL commands:
select library.lib_id, library.name from library join bac on
library.bac_id=bac.id where bac.lib_name="Medicago";
select seq_name from sequence where seq_name like 'MBE%'
and trash is null; | [
"%prog",
"libs",
"libfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/db.py#L125-L157 | train | 200,403 |
tanghaibao/jcvi | jcvi/utils/db.py | pull | def pull(args):
"""
%prog pull libfile
Pull the sequences using the first column in the libfile.
"""
p = OptionParser(pull.__doc__)
p.set_db_opts(dbname="mtg2", credentials=None)
p.add_option("--frag", default=False, action="store_true",
help="The command to pull sequences from db [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
libfile, = args
dbname = opts.dbname
frag = opts.frag
fp = open(libfile)
hostname, username, password = get_profile()
for row in fp:
lib_id, name = row.split("|", 1)
sqlfile = lib_id + ".sql"
if not op.exists(sqlfile):
fw = open(sqlfile, "w")
print("select seq_name from sequence where seq_name like" + \
" '{0}%' and trash is null".format(lib_id), file=fw)
fw.close()
if frag:
cmd = "pullfrag -D {0} -n {1}.sql -o {1} -q -S {2}".format(dbname, lib_id, hostname)
cmd += " -U {0} -P {1}".format(username, password)
else:
cmd = "pullseq -D {0} -n {1}.sql -o {1} -q".format(dbname, lib_id)
sh(cmd) | python | def pull(args):
"""
%prog pull libfile
Pull the sequences using the first column in the libfile.
"""
p = OptionParser(pull.__doc__)
p.set_db_opts(dbname="mtg2", credentials=None)
p.add_option("--frag", default=False, action="store_true",
help="The command to pull sequences from db [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
libfile, = args
dbname = opts.dbname
frag = opts.frag
fp = open(libfile)
hostname, username, password = get_profile()
for row in fp:
lib_id, name = row.split("|", 1)
sqlfile = lib_id + ".sql"
if not op.exists(sqlfile):
fw = open(sqlfile, "w")
print("select seq_name from sequence where seq_name like" + \
" '{0}%' and trash is null".format(lib_id), file=fw)
fw.close()
if frag:
cmd = "pullfrag -D {0} -n {1}.sql -o {1} -q -S {2}".format(dbname, lib_id, hostname)
cmd += " -U {0} -P {1}".format(username, password)
else:
cmd = "pullseq -D {0} -n {1}.sql -o {1} -q".format(dbname, lib_id)
sh(cmd) | [
"def",
"pull",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"pull",
".",
"__doc__",
")",
"p",
".",
"set_db_opts",
"(",
"dbname",
"=",
"\"mtg2\"",
",",
"credentials",
"=",
"None",
")",
"p",
".",
"add_option",
"(",
"\"--frag\"",
",",
"default",
... | %prog pull libfile
Pull the sequences using the first column in the libfile. | [
"%prog",
"pull",
"libfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/db.py#L160-L197 | train | 200,404 |
tanghaibao/jcvi | jcvi/assembly/amos.py | read_record | def read_record(fp, first_line=None):
"""
Read a record from a file of AMOS messages
On success returns a Message object
On end of file raises EOFError
"""
if first_line is None:
first_line = fp.readline()
if not first_line:
raise EOFError()
match = _START.match(first_line)
if not match:
raise Exception('Bad start of message', first_line)
type = match.group(1)
message = Message(type)
while True:
row = fp.readline()
match = _MULTILINE_FIELD.match(row)
if match:
key = match.group(1)
val = ""
while row:
pos = fp.tell()
row = fp.readline()
if row[0] in '.':
break
elif row[0] in '{}':
fp.seek(pos) # put the line back
break
val += row
message.contents.append((key, val, True))
continue
match = _FIELD.match(row)
if match:
key, val = match.group(1), match.group(2)
message.contents.append((key, val, False))
continue
match = _START.match(row)
if match:
message.append(read_record(fp, row))
continue
if row[0] == '}':
break
raise Exception('Bad line', row)
return message | python | def read_record(fp, first_line=None):
"""
Read a record from a file of AMOS messages
On success returns a Message object
On end of file raises EOFError
"""
if first_line is None:
first_line = fp.readline()
if not first_line:
raise EOFError()
match = _START.match(first_line)
if not match:
raise Exception('Bad start of message', first_line)
type = match.group(1)
message = Message(type)
while True:
row = fp.readline()
match = _MULTILINE_FIELD.match(row)
if match:
key = match.group(1)
val = ""
while row:
pos = fp.tell()
row = fp.readline()
if row[0] in '.':
break
elif row[0] in '{}':
fp.seek(pos) # put the line back
break
val += row
message.contents.append((key, val, True))
continue
match = _FIELD.match(row)
if match:
key, val = match.group(1), match.group(2)
message.contents.append((key, val, False))
continue
match = _START.match(row)
if match:
message.append(read_record(fp, row))
continue
if row[0] == '}':
break
raise Exception('Bad line', row)
return message | [
"def",
"read_record",
"(",
"fp",
",",
"first_line",
"=",
"None",
")",
":",
"if",
"first_line",
"is",
"None",
":",
"first_line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"first_line",
":",
"raise",
"EOFError",
"(",
")",
"match",
"=",
"_START",... | Read a record from a file of AMOS messages
On success returns a Message object
On end of file raises EOFError | [
"Read",
"a",
"record",
"from",
"a",
"file",
"of",
"AMOS",
"messages"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/amos.py#L67-L123 | train | 200,405 |
tanghaibao/jcvi | jcvi/assembly/amos.py | filter | def filter(args):
"""
%prog filter frgfile idsfile
Removes the reads from frgfile that are indicated as duplicates in the
clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to
include in the filtered frgfile. See apps.cdhit.ids().
"""
p = OptionParser(filter.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
frgfile, idsfile = args
assert frgfile.endswith(".frg")
fp = open(idsfile)
allowed = set(x.strip() for x in fp)
logging.debug("A total of {0} allowed ids loaded.".format(len(allowed)))
newfrgfile = frgfile.replace(".frg", ".filtered.frg")
fp = open(frgfile)
fw = open(newfrgfile, "w")
nfrags, discarded_frags = 0, 0
nmates, discarded_mates = 0, 0
for rec in iter_records(fp):
if rec.type == "FRG":
readname = rec.get_field("acc")
readname = readname.rstrip("ab")
nfrags += 1
if readname not in allowed:
discarded_frags += 1
continue
if rec.type == "LKG":
readname = rec.get_field("frg")
readname = readname.rstrip("ab")
nmates += 1
if readname not in allowed:
discarded_mates += 1
continue
print(rec, file=fw)
# Print out a summary
survived_frags = nfrags - discarded_frags
survived_mates = nmates - discarded_mates
print("Survived fragments: {0}".\
format(percentage(survived_frags, nfrags)), file=sys.stderr)
print("Survived mates: {0}".\
format(percentage(survived_mates, nmates)), file=sys.stderr) | python | def filter(args):
"""
%prog filter frgfile idsfile
Removes the reads from frgfile that are indicated as duplicates in the
clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to
include in the filtered frgfile. See apps.cdhit.ids().
"""
p = OptionParser(filter.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
frgfile, idsfile = args
assert frgfile.endswith(".frg")
fp = open(idsfile)
allowed = set(x.strip() for x in fp)
logging.debug("A total of {0} allowed ids loaded.".format(len(allowed)))
newfrgfile = frgfile.replace(".frg", ".filtered.frg")
fp = open(frgfile)
fw = open(newfrgfile, "w")
nfrags, discarded_frags = 0, 0
nmates, discarded_mates = 0, 0
for rec in iter_records(fp):
if rec.type == "FRG":
readname = rec.get_field("acc")
readname = readname.rstrip("ab")
nfrags += 1
if readname not in allowed:
discarded_frags += 1
continue
if rec.type == "LKG":
readname = rec.get_field("frg")
readname = readname.rstrip("ab")
nmates += 1
if readname not in allowed:
discarded_mates += 1
continue
print(rec, file=fw)
# Print out a summary
survived_frags = nfrags - discarded_frags
survived_mates = nmates - discarded_mates
print("Survived fragments: {0}".\
format(percentage(survived_frags, nfrags)), file=sys.stderr)
print("Survived mates: {0}".\
format(percentage(survived_mates, nmates)), file=sys.stderr) | [
"def",
"filter",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"filter",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"n... | %prog filter frgfile idsfile
Removes the reads from frgfile that are indicated as duplicates in the
clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to
include in the filtered frgfile. See apps.cdhit.ids(). | [
"%prog",
"filter",
"frgfile",
"idsfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/amos.py#L148-L198 | train | 200,406 |
tanghaibao/jcvi | jcvi/assembly/amos.py | frg | def frg(args):
"""
%prog frg frgfile
Extract FASTA sequences from frg reads.
"""
p = OptionParser(frg.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fastafile = frgfile.rsplit(".", 1)[0] + ".fasta"
fp = open(frgfile)
fw = open(fastafile, "w")
for rec in iter_records(fp):
if rec.type != "FRG":
continue
id = rec.get_field("acc")
seq = rec.get_field("seq")
s = SeqRecord(Seq(seq), id=id, description="")
SeqIO.write([s], fw, "fasta")
fw.close() | python | def frg(args):
"""
%prog frg frgfile
Extract FASTA sequences from frg reads.
"""
p = OptionParser(frg.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fastafile = frgfile.rsplit(".", 1)[0] + ".fasta"
fp = open(frgfile)
fw = open(fastafile, "w")
for rec in iter_records(fp):
if rec.type != "FRG":
continue
id = rec.get_field("acc")
seq = rec.get_field("seq")
s = SeqRecord(Seq(seq), id=id, description="")
SeqIO.write([s], fw, "fasta")
fw.close() | [
"def",
"frg",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"frg",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"p",
"... | %prog frg frgfile
Extract FASTA sequences from frg reads. | [
"%prog",
"frg",
"frgfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/amos.py#L201-L226 | train | 200,407 |
tanghaibao/jcvi | jcvi/assembly/amos.py | asm | def asm(args):
"""
%prog asm asmfile
Extract FASTA sequences from asm reads.
"""
p = OptionParser(asm.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
asmfile, = args
prefix = asmfile.rsplit(".", 1)[0]
ctgfastafile = prefix + ".ctg.fasta"
scffastafile = prefix + ".scf.fasta"
fp = open(asmfile)
ctgfw = open(ctgfastafile, "w")
scffw = open(scffastafile, "w")
for rec in iter_records(fp):
type = rec.type
if type == "CCO":
fw = ctgfw
pp = "ctg"
elif type == "SCF":
fw = scffw
pp = "scf"
else:
continue
id = rec.get_field("acc")
id = id.translate(None, "()").split(",")[0]
seq = rec.get_field("cns").translate(None, "-")
s = SeqRecord(Seq(seq), id=pp + id, description="")
SeqIO.write([s], fw, "fasta")
fw.flush()
fw.close() | python | def asm(args):
"""
%prog asm asmfile
Extract FASTA sequences from asm reads.
"""
p = OptionParser(asm.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
asmfile, = args
prefix = asmfile.rsplit(".", 1)[0]
ctgfastafile = prefix + ".ctg.fasta"
scffastafile = prefix + ".scf.fasta"
fp = open(asmfile)
ctgfw = open(ctgfastafile, "w")
scffw = open(scffastafile, "w")
for rec in iter_records(fp):
type = rec.type
if type == "CCO":
fw = ctgfw
pp = "ctg"
elif type == "SCF":
fw = scffw
pp = "scf"
else:
continue
id = rec.get_field("acc")
id = id.translate(None, "()").split(",")[0]
seq = rec.get_field("cns").translate(None, "-")
s = SeqRecord(Seq(seq), id=pp + id, description="")
SeqIO.write([s], fw, "fasta")
fw.flush()
fw.close() | [
"def",
"asm",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"asm",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"p",
"... | %prog asm asmfile
Extract FASTA sequences from asm reads. | [
"%prog",
"asm",
"asmfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/amos.py#L229-L267 | train | 200,408 |
tanghaibao/jcvi | jcvi/assembly/amos.py | count | def count(args):
"""
%prog count frgfile
Count each type of messages
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fp = open(frgfile)
counts = defaultdict(int)
for rec in iter_records(fp):
counts[rec.type] += 1
for type, cnt in sorted(counts.items()):
print('{0}: {1}'.format(type, cnt), file=sys.stderr) | python | def count(args):
"""
%prog count frgfile
Count each type of messages
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
frgfile, = args
fp = open(frgfile)
counts = defaultdict(int)
for rec in iter_records(fp):
counts[rec.type] += 1
for type, cnt in sorted(counts.items()):
print('{0}: {1}'.format(type, cnt), file=sys.stderr) | [
"def",
"count",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"count",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"p",... | %prog count frgfile
Count each type of messages | [
"%prog",
"count",
"frgfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/amos.py#L270-L290 | train | 200,409 |
tanghaibao/jcvi | jcvi/projects/heterosis.py | prepare | def prepare(args):
"""
%prog prepare countfolder families
Parse list of count files and group per family into families folder.
"""
p = OptionParser(prepare.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
counts, families = args
countfiles = glob(op.join(counts, "*.count"))
countsdb = defaultdict(list)
for c in countfiles:
rs = RiceSample(c)
countsdb[(rs.tissue, rs.ind)].append(rs)
# Merge duplicates - data sequenced in different batches
key = lambda x: (x.label, x.rep)
for (tissue, ind), rs in sorted(countsdb.items()):
rs.sort(key=key)
nrs = len(rs)
for i in xrange(nrs):
ri = rs[i]
if not ri.working:
continue
for j in xrange(i + 1, nrs):
rj = rs[j]
if key(ri) != key(rj):
continue
ri.merge(rj)
rj.working = False
countsdb[(tissue, ind)] = [x for x in rs if x.working]
# Group into families
mkdir("families")
for (tissue, ind), r in sorted(countsdb.items()):
r = list(r)
if r[0].label != "F1":
continue
P1, P2 = r[0].P1, r[0].P2
P1, P2 = countsdb[(tissue, P1)], countsdb[(tissue, P2)]
rs = P1 + P2 + r
groups = [1] * len(P1) + [2] * len(P2) + [3] * len(r)
assert len(rs) == len(groups)
outfile = "-".join((tissue, ind))
merge_counts(rs, op.join(families, outfile))
groupsfile = outfile + ".groups"
fw = open(op.join(families, groupsfile), "w")
print(",".join(str(x) for x in groups), file=fw)
fw.close() | python | def prepare(args):
"""
%prog prepare countfolder families
Parse list of count files and group per family into families folder.
"""
p = OptionParser(prepare.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
counts, families = args
countfiles = glob(op.join(counts, "*.count"))
countsdb = defaultdict(list)
for c in countfiles:
rs = RiceSample(c)
countsdb[(rs.tissue, rs.ind)].append(rs)
# Merge duplicates - data sequenced in different batches
key = lambda x: (x.label, x.rep)
for (tissue, ind), rs in sorted(countsdb.items()):
rs.sort(key=key)
nrs = len(rs)
for i in xrange(nrs):
ri = rs[i]
if not ri.working:
continue
for j in xrange(i + 1, nrs):
rj = rs[j]
if key(ri) != key(rj):
continue
ri.merge(rj)
rj.working = False
countsdb[(tissue, ind)] = [x for x in rs if x.working]
# Group into families
mkdir("families")
for (tissue, ind), r in sorted(countsdb.items()):
r = list(r)
if r[0].label != "F1":
continue
P1, P2 = r[0].P1, r[0].P2
P1, P2 = countsdb[(tissue, P1)], countsdb[(tissue, P2)]
rs = P1 + P2 + r
groups = [1] * len(P1) + [2] * len(P2) + [3] * len(r)
assert len(rs) == len(groups)
outfile = "-".join((tissue, ind))
merge_counts(rs, op.join(families, outfile))
groupsfile = outfile + ".groups"
fw = open(op.join(families, groupsfile), "w")
print(",".join(str(x) for x in groups), file=fw)
fw.close() | [
"def",
"prepare",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"prepare",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | %prog prepare countfolder families
Parse list of count files and group per family into families folder. | [
"%prog",
"prepare",
"countfolder",
"families"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/heterosis.py#L131-L184 | train | 200,410 |
tanghaibao/jcvi | jcvi/algorithms/formula.py | outlier_cutoff | def outlier_cutoff(a, threshold=3.5):
"""
Iglewicz and Hoaglin's robust, returns the cutoff values - lower bound and
upper bound.
"""
A = np.array(a, dtype=float)
M = np.median(A)
D = np.absolute(A - M)
MAD = np.median(D)
C = threshold / .67449 * MAD
return M - C, M + C | python | def outlier_cutoff(a, threshold=3.5):
"""
Iglewicz and Hoaglin's robust, returns the cutoff values - lower bound and
upper bound.
"""
A = np.array(a, dtype=float)
M = np.median(A)
D = np.absolute(A - M)
MAD = np.median(D)
C = threshold / .67449 * MAD
return M - C, M + C | [
"def",
"outlier_cutoff",
"(",
"a",
",",
"threshold",
"=",
"3.5",
")",
":",
"A",
"=",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"float",
")",
"M",
"=",
"np",
".",
"median",
"(",
"A",
")",
"D",
"=",
"np",
".",
"absolute",
"(",
"A",
"-",
... | Iglewicz and Hoaglin's robust, returns the cutoff values - lower bound and
upper bound. | [
"Iglewicz",
"and",
"Hoaglin",
"s",
"robust",
"returns",
"the",
"cutoff",
"values",
"-",
"lower",
"bound",
"and",
"upper",
"bound",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/formula.py#L137-L147 | train | 200,411 |
tanghaibao/jcvi | jcvi/apps/biomart.py | bed | def bed(args):
"""
%prog bed genes.ids
Get gene bed from phytozome. `genes.ids` contains the list of gene you want
to pull from Phytozome. Write output to .bed file.
"""
p = OptionParser(bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
idsfile, = args
ids = set(x.strip() for x in open(idsfile))
data = get_bed_from_phytozome(list(ids))
pf = idsfile.rsplit(".", 1)[0]
bedfile = pf + ".bed"
fw = open(bedfile, "w")
for i, row in enumerate(data):
row = row.strip()
if row == "":
continue
print(row, file=fw)
logging.debug("A total of {0} records written to `{1}`.".format(i + 1, bedfile)) | python | def bed(args):
"""
%prog bed genes.ids
Get gene bed from phytozome. `genes.ids` contains the list of gene you want
to pull from Phytozome. Write output to .bed file.
"""
p = OptionParser(bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
idsfile, = args
ids = set(x.strip() for x in open(idsfile))
data = get_bed_from_phytozome(list(ids))
pf = idsfile.rsplit(".", 1)[0]
bedfile = pf + ".bed"
fw = open(bedfile, "w")
for i, row in enumerate(data):
row = row.strip()
if row == "":
continue
print(row, file=fw)
logging.debug("A total of {0} records written to `{1}`.".format(i + 1, bedfile)) | [
"def",
"bed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | %prog bed genes.ids
Get gene bed from phytozome. `genes.ids` contains the list of gene you want
to pull from Phytozome. Write output to .bed file. | [
"%prog",
"bed",
"genes",
".",
"ids"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/biomart.py#L297-L324 | train | 200,412 |
tanghaibao/jcvi | jcvi/annotation/depth.py | bed | def bed(args):
"""
%prog bed binfile fastafile
Write bed files where the bases have at least certain depth.
"""
p = OptionParser(bed.__doc__)
p.add_option("-o", dest="output", default="stdout",
help="Output file name [default: %default]")
p.add_option("--cutoff", dest="cutoff", default=10, type="int",
help="Minimum read depth to report intervals [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
binfile, fastafile = args
fw = must_open(opts.output, "w")
cutoff = opts.cutoff
assert cutoff >= 0, "Need non-negative cutoff"
b = BinFile(binfile)
ar = b.array
fastasize, sizes, offsets = get_offsets(fastafile)
s = Sizes(fastafile)
for ctg, ctglen in s.iter_sizes():
offset = offsets[ctg]
subarray = ar[offset:offset + ctglen]
key = lambda x: x[1] >= cutoff
for tf, array_elements in groupby(enumerate(subarray), key=key):
array_elements = list(array_elements)
if not tf:
continue
# 0-based system => 1-based system
start = array_elements[0][0] + 1
end = array_elements[-1][0] + 1
mean_depth = sum([x[1] for x in array_elements]) / \
len(array_elements)
mean_depth = int(mean_depth)
name = "na"
print("\t".join(str(x) for x in (ctg, \
start - 1, end, name, mean_depth)), file=fw) | python | def bed(args):
"""
%prog bed binfile fastafile
Write bed files where the bases have at least certain depth.
"""
p = OptionParser(bed.__doc__)
p.add_option("-o", dest="output", default="stdout",
help="Output file name [default: %default]")
p.add_option("--cutoff", dest="cutoff", default=10, type="int",
help="Minimum read depth to report intervals [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
binfile, fastafile = args
fw = must_open(opts.output, "w")
cutoff = opts.cutoff
assert cutoff >= 0, "Need non-negative cutoff"
b = BinFile(binfile)
ar = b.array
fastasize, sizes, offsets = get_offsets(fastafile)
s = Sizes(fastafile)
for ctg, ctglen in s.iter_sizes():
offset = offsets[ctg]
subarray = ar[offset:offset + ctglen]
key = lambda x: x[1] >= cutoff
for tf, array_elements in groupby(enumerate(subarray), key=key):
array_elements = list(array_elements)
if not tf:
continue
# 0-based system => 1-based system
start = array_elements[0][0] + 1
end = array_elements[-1][0] + 1
mean_depth = sum([x[1] for x in array_elements]) / \
len(array_elements)
mean_depth = int(mean_depth)
name = "na"
print("\t".join(str(x) for x in (ctg, \
start - 1, end, name, mean_depth)), file=fw) | [
"def",
"bed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-o\"",
",",
"dest",
"=",
"\"output\"",
",",
"default",
"=",
"\"stdout\"",
",",
"help",
"=",
"\"Output file name [default: %defau... | %prog bed binfile fastafile
Write bed files where the bases have at least certain depth. | [
"%prog",
"bed",
"binfile",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/depth.py#L57-L102 | train | 200,413 |
tanghaibao/jcvi | jcvi/annotation/depth.py | query | def query(args):
"""
%prog query binfile fastafile ctgID baseID
Get the depth at a particular base.
"""
p = OptionParser(query.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
binfile, fastafile, ctgID, baseID = args
b = BinFile(binfile, fastafile)
ar = b.mmarray
fastasize, sizes, offsets = get_offsets(fastafile)
oi = offsets[ctgID] + int(baseID) - 1
print("\t".join((ctgID, baseID, str(ar[oi])))) | python | def query(args):
"""
%prog query binfile fastafile ctgID baseID
Get the depth at a particular base.
"""
p = OptionParser(query.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
binfile, fastafile, ctgID, baseID = args
b = BinFile(binfile, fastafile)
ar = b.mmarray
fastasize, sizes, offsets = get_offsets(fastafile)
oi = offsets[ctgID] + int(baseID) - 1
print("\t".join((ctgID, baseID, str(ar[oi])))) | [
"def",
"query",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"query",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"4",
":",
"sys",
".",
"exit",
"(",
"not... | %prog query binfile fastafile ctgID baseID
Get the depth at a particular base. | [
"%prog",
"query",
"binfile",
"fastafile",
"ctgID",
"baseID"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/depth.py#L144-L162 | train | 200,414 |
tanghaibao/jcvi | jcvi/annotation/depth.py | count | def count(args):
"""
%prog count t.coveragePerBase fastafile
Serialize the genomeCoverage results. The coordinate system of the count array
will be based on the fastafile.
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
coveragefile, fastafile = args
countsfile = coveragefile.split(".")[0] + ".bin"
if op.exists(countsfile):
logging.error("`{0}` file exists. Remove before proceed."\
.format(countsfile))
return
fastasize, sizes, offsets = get_offsets(fastafile)
logging.debug("Initialize array of uint8 with size {0}".format(fastasize))
ar = np.zeros(fastasize, dtype=np.uint8)
update_array(ar, coveragefile, sizes, offsets)
ar.tofile(countsfile)
logging.debug("Array written to `{0}`".format(countsfile)) | python | def count(args):
"""
%prog count t.coveragePerBase fastafile
Serialize the genomeCoverage results. The coordinate system of the count array
will be based on the fastafile.
"""
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
coveragefile, fastafile = args
countsfile = coveragefile.split(".")[0] + ".bin"
if op.exists(countsfile):
logging.error("`{0}` file exists. Remove before proceed."\
.format(countsfile))
return
fastasize, sizes, offsets = get_offsets(fastafile)
logging.debug("Initialize array of uint8 with size {0}".format(fastasize))
ar = np.zeros(fastasize, dtype=np.uint8)
update_array(ar, coveragefile, sizes, offsets)
ar.tofile(countsfile)
logging.debug("Array written to `{0}`".format(countsfile)) | [
"def",
"count",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"count",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"not... | %prog count t.coveragePerBase fastafile
Serialize the genomeCoverage results. The coordinate system of the count array
will be based on the fastafile. | [
"%prog",
"count",
"t",
".",
"coveragePerBase",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/depth.py#L197-L225 | train | 200,415 |
tanghaibao/jcvi | jcvi/algorithms/lpsolve.py | edges_to_path | def edges_to_path(edges):
"""
Connect edges and return a path.
"""
if not edges:
return None
G = edges_to_graph(edges)
path = nx.topological_sort(G)
return path | python | def edges_to_path(edges):
"""
Connect edges and return a path.
"""
if not edges:
return None
G = edges_to_graph(edges)
path = nx.topological_sort(G)
return path | [
"def",
"edges_to_path",
"(",
"edges",
")",
":",
"if",
"not",
"edges",
":",
"return",
"None",
"G",
"=",
"edges_to_graph",
"(",
"edges",
")",
"path",
"=",
"nx",
".",
"topological_sort",
"(",
"G",
")",
"return",
"path"
] | Connect edges and return a path. | [
"Connect",
"edges",
"and",
"return",
"a",
"path",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lpsolve.py#L274-L283 | train | 200,416 |
tanghaibao/jcvi | jcvi/algorithms/maxsum.py | max_sum | def max_sum(a):
"""
For an input array a, output the range that gives the largest sum
>>> max_sum([4, 4, 9, -5, -6, -1, 5, -6, -8, 9])
(17, 0, 2)
>>> max_sum([8, -10, 10, -9, -6, 9, -7, -4, -10, -8])
(10, 2, 2)
>>> max_sum([10, 1, -10, -8, 6, 10, -10, 6, -3, 10])
(19, 4, 9)
"""
max_sum, max_start_index, max_end_index = -Infinity, 0, 0
current_max_sum = 0
current_start_index = 0
for current_end_index, x in enumerate(a):
current_max_sum += x
if current_max_sum > max_sum:
max_sum, max_start_index, max_end_index = current_max_sum, \
current_start_index, current_end_index
if current_max_sum < 0:
current_max_sum = 0
current_start_index = current_end_index + 1
return max_sum, max_start_index, max_end_index | python | def max_sum(a):
"""
For an input array a, output the range that gives the largest sum
>>> max_sum([4, 4, 9, -5, -6, -1, 5, -6, -8, 9])
(17, 0, 2)
>>> max_sum([8, -10, 10, -9, -6, 9, -7, -4, -10, -8])
(10, 2, 2)
>>> max_sum([10, 1, -10, -8, 6, 10, -10, 6, -3, 10])
(19, 4, 9)
"""
max_sum, max_start_index, max_end_index = -Infinity, 0, 0
current_max_sum = 0
current_start_index = 0
for current_end_index, x in enumerate(a):
current_max_sum += x
if current_max_sum > max_sum:
max_sum, max_start_index, max_end_index = current_max_sum, \
current_start_index, current_end_index
if current_max_sum < 0:
current_max_sum = 0
current_start_index = current_end_index + 1
return max_sum, max_start_index, max_end_index | [
"def",
"max_sum",
"(",
"a",
")",
":",
"max_sum",
",",
"max_start_index",
",",
"max_end_index",
"=",
"-",
"Infinity",
",",
"0",
",",
"0",
"current_max_sum",
"=",
"0",
"current_start_index",
"=",
"0",
"for",
"current_end_index",
",",
"x",
"in",
"enumerate",
... | For an input array a, output the range that gives the largest sum
>>> max_sum([4, 4, 9, -5, -6, -1, 5, -6, -8, 9])
(17, 0, 2)
>>> max_sum([8, -10, 10, -9, -6, 9, -7, -4, -10, -8])
(10, 2, 2)
>>> max_sum([10, 1, -10, -8, 6, 10, -10, 6, -3, 10])
(19, 4, 9) | [
"For",
"an",
"input",
"array",
"a",
"output",
"the",
"range",
"that",
"gives",
"the",
"largest",
"sum"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/maxsum.py#L14-L38 | train | 200,417 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | silicosoma | def silicosoma(args):
"""
%prog silicosoma in.silico > out.soma
Convert .silico to .soma file.
Format of .silico
A text file containing in-silico digested contigs. This file contains pairs
of lines. The first line in each pair constains an identifier, this contig
length in bp, and the number of restriction sites, separated by white space.
The second line contains a white space delimited list of the restriction
site positions.
Format of .soma
Each line of the text file contains two decimal numbers: The size of the
fragment and the standard deviation (both in kb), separated by white space.
The standard deviation is ignored.
"""
p = OptionParser(silicosoma.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
silicofile, = args
fp = must_open(silicofile)
fw = must_open(opts.outfile, "w")
next(fp)
positions = [int(x) for x in fp.next().split()]
for a, b in pairwise(positions):
assert a <= b
fragsize = int(round((b - a) / 1000.)) # kb
if fragsize:
print(fragsize, 0, file=fw) | python | def silicosoma(args):
"""
%prog silicosoma in.silico > out.soma
Convert .silico to .soma file.
Format of .silico
A text file containing in-silico digested contigs. This file contains pairs
of lines. The first line in each pair constains an identifier, this contig
length in bp, and the number of restriction sites, separated by white space.
The second line contains a white space delimited list of the restriction
site positions.
Format of .soma
Each line of the text file contains two decimal numbers: The size of the
fragment and the standard deviation (both in kb), separated by white space.
The standard deviation is ignored.
"""
p = OptionParser(silicosoma.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
silicofile, = args
fp = must_open(silicofile)
fw = must_open(opts.outfile, "w")
next(fp)
positions = [int(x) for x in fp.next().split()]
for a, b in pairwise(positions):
assert a <= b
fragsize = int(round((b - a) / 1000.)) # kb
if fragsize:
print(fragsize, 0, file=fw) | [
"def",
"silicosoma",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"silicosoma",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!="... | %prog silicosoma in.silico > out.soma
Convert .silico to .soma file.
Format of .silico
A text file containing in-silico digested contigs. This file contains pairs
of lines. The first line in each pair constains an identifier, this contig
length in bp, and the number of restriction sites, separated by white space.
The second line contains a white space delimited list of the restriction
site positions.
Format of .soma
Each line of the text file contains two decimal numbers: The size of the
fragment and the standard deviation (both in kb), separated by white space.
The standard deviation is ignored. | [
"%prog",
"silicosoma",
"in",
".",
"silico",
">",
"out",
".",
"soma"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L182-L216 | train | 200,418 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | condense | def condense(args):
"""
%prog condense OM.bed
Merge split alignments in OM bed.
"""
from itertools import groupby
from jcvi.assembly.patch import merge_ranges
p = OptionParser(condense.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
bed = Bed(bedfile, sorted=False)
key = lambda x: (x.seqid, x.start, x.end)
for k, sb in groupby(bed, key=key):
sb = list(sb)
b = sb[0]
chr, start, end, strand = merge_ranges(sb)
id = "{0}:{1}-{2}".format(chr, start, end)
b.accn = id
print(b) | python | def condense(args):
"""
%prog condense OM.bed
Merge split alignments in OM bed.
"""
from itertools import groupby
from jcvi.assembly.patch import merge_ranges
p = OptionParser(condense.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
bed = Bed(bedfile, sorted=False)
key = lambda x: (x.seqid, x.start, x.end)
for k, sb in groupby(bed, key=key):
sb = list(sb)
b = sb[0]
chr, start, end, strand = merge_ranges(sb)
id = "{0}:{1}-{2}".format(chr, start, end)
b.accn = id
print(b) | [
"def",
"condense",
"(",
"args",
")",
":",
"from",
"itertools",
"import",
"groupby",
"from",
"jcvi",
".",
"assembly",
".",
"patch",
"import",
"merge_ranges",
"p",
"=",
"OptionParser",
"(",
"condense",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".... | %prog condense OM.bed
Merge split alignments in OM bed. | [
"%prog",
"condense",
"OM",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L219-L244 | train | 200,419 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | chimera | def chimera(args):
"""
%prog chimera bedfile
Scan the bed file to break scaffolds that multi-maps.
"""
p = OptionParser(chimera.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
bed = Bed(bedfile)
selected = select_bed(bed)
mapped = defaultdict(set) # scaffold => chr
chimerabed = "chimera.bed"
fw = open(chimerabed, "w")
for b in selected:
scf = range_parse(b.accn).seqid
chr = b.seqid
mapped[scf].add(chr)
nchimera = 0
for s, chrs in sorted(mapped.items()):
if len(chrs) == 1:
continue
print("=" * 80, file=sys.stderr)
print("{0} mapped to multiple locations: {1}".\
format(s, ",".join(sorted(chrs))), file=sys.stderr)
ranges = []
for b in selected:
rr = range_parse(b.accn)
scf = rr.seqid
if scf == s:
print(b, file=sys.stderr)
ranges.append(rr)
# Identify breakpoints
ranges.sort(key=lambda x: (x.seqid, x.start, x.end))
for a, b in pairwise(ranges):
seqid = a.seqid
if seqid != b.seqid:
continue
start, end = a.end, b.start
if start > end:
start, end = end, start
chimeraline = "\t".join(str(x) for x in (seqid, start, end))
print(chimeraline, file=fw)
print(chimeraline, file=sys.stderr)
nchimera += 1
fw.close()
logging.debug("A total of {0} junctions written to `{1}`.".\
format(nchimera, chimerabed)) | python | def chimera(args):
"""
%prog chimera bedfile
Scan the bed file to break scaffolds that multi-maps.
"""
p = OptionParser(chimera.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
bed = Bed(bedfile)
selected = select_bed(bed)
mapped = defaultdict(set) # scaffold => chr
chimerabed = "chimera.bed"
fw = open(chimerabed, "w")
for b in selected:
scf = range_parse(b.accn).seqid
chr = b.seqid
mapped[scf].add(chr)
nchimera = 0
for s, chrs in sorted(mapped.items()):
if len(chrs) == 1:
continue
print("=" * 80, file=sys.stderr)
print("{0} mapped to multiple locations: {1}".\
format(s, ",".join(sorted(chrs))), file=sys.stderr)
ranges = []
for b in selected:
rr = range_parse(b.accn)
scf = rr.seqid
if scf == s:
print(b, file=sys.stderr)
ranges.append(rr)
# Identify breakpoints
ranges.sort(key=lambda x: (x.seqid, x.start, x.end))
for a, b in pairwise(ranges):
seqid = a.seqid
if seqid != b.seqid:
continue
start, end = a.end, b.start
if start > end:
start, end = end, start
chimeraline = "\t".join(str(x) for x in (seqid, start, end))
print(chimeraline, file=fw)
print(chimeraline, file=sys.stderr)
nchimera += 1
fw.close()
logging.debug("A total of {0} junctions written to `{1}`.".\
format(nchimera, chimerabed)) | [
"def",
"chimera",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"chimera",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog chimera bedfile
Scan the bed file to break scaffolds that multi-maps. | [
"%prog",
"chimera",
"bedfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L247-L304 | train | 200,420 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | select_bed | def select_bed(bed):
"""
Return non-overlapping set of ranges, choosing high scoring blocks over low
scoring alignments when there are conflicts.
"""
ranges = [Range(x.seqid, x.start, x.end, float(x.score), i) for i, x in enumerate(bed)]
selected, score = range_chain(ranges)
selected = [bed[x.id] for x in selected]
return selected | python | def select_bed(bed):
"""
Return non-overlapping set of ranges, choosing high scoring blocks over low
scoring alignments when there are conflicts.
"""
ranges = [Range(x.seqid, x.start, x.end, float(x.score), i) for i, x in enumerate(bed)]
selected, score = range_chain(ranges)
selected = [bed[x.id] for x in selected]
return selected | [
"def",
"select_bed",
"(",
"bed",
")",
":",
"ranges",
"=",
"[",
"Range",
"(",
"x",
".",
"seqid",
",",
"x",
".",
"start",
",",
"x",
".",
"end",
",",
"float",
"(",
"x",
".",
"score",
")",
",",
"i",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
... | Return non-overlapping set of ranges, choosing high scoring blocks over low
scoring alignments when there are conflicts. | [
"Return",
"non",
"-",
"overlapping",
"set",
"of",
"ranges",
"choosing",
"high",
"scoring",
"blocks",
"over",
"low",
"scoring",
"alignments",
"when",
"there",
"are",
"conflicts",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L307-L316 | train | 200,421 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | fasta | def fasta(args):
"""
%prog fasta bedfile scf.fasta pseudomolecules.fasta
Use OM bed to scaffold and create pseudomolecules. bedfile can be generated
by running jcvi.assembly.opticalmap bed --blockonly
"""
from jcvi.formats.sizes import Sizes
from jcvi.formats.agp import OO, build
p = OptionParser(fasta.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
bedfile, scffasta, pmolfasta = args
pf = bedfile.rsplit(".", 1)[0]
bed = Bed(bedfile)
selected = select_bed(bed)
oo = OO()
seen = set()
sizes = Sizes(scffasta).mapping
agpfile = pf + ".agp"
agp = open(agpfile, "w")
for b in selected:
scf = range_parse(b.accn).seqid
chr = b.seqid
cs = (chr, scf)
if cs not in seen:
oo.add(chr, scf, sizes[scf], b.strand)
seen.add(cs)
else:
logging.debug("Seen {0}, ignored.".format(cs))
oo.write_AGP(agp, gaptype="contig")
agp.close()
build([agpfile, scffasta, pmolfasta]) | python | def fasta(args):
"""
%prog fasta bedfile scf.fasta pseudomolecules.fasta
Use OM bed to scaffold and create pseudomolecules. bedfile can be generated
by running jcvi.assembly.opticalmap bed --blockonly
"""
from jcvi.formats.sizes import Sizes
from jcvi.formats.agp import OO, build
p = OptionParser(fasta.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
bedfile, scffasta, pmolfasta = args
pf = bedfile.rsplit(".", 1)[0]
bed = Bed(bedfile)
selected = select_bed(bed)
oo = OO()
seen = set()
sizes = Sizes(scffasta).mapping
agpfile = pf + ".agp"
agp = open(agpfile, "w")
for b in selected:
scf = range_parse(b.accn).seqid
chr = b.seqid
cs = (chr, scf)
if cs not in seen:
oo.add(chr, scf, sizes[scf], b.strand)
seen.add(cs)
else:
logging.debug("Seen {0}, ignored.".format(cs))
oo.write_AGP(agp, gaptype="contig")
agp.close()
build([agpfile, scffasta, pmolfasta]) | [
"def",
"fasta",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"from",
"jcvi",
".",
"formats",
".",
"agp",
"import",
"OO",
",",
"build",
"p",
"=",
"OptionParser",
"(",
"fasta",
".",
"__doc__",
")",
"opts",
","... | %prog fasta bedfile scf.fasta pseudomolecules.fasta
Use OM bed to scaffold and create pseudomolecules. bedfile can be generated
by running jcvi.assembly.opticalmap bed --blockonly | [
"%prog",
"fasta",
"bedfile",
"scf",
".",
"fasta",
"pseudomolecules",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L319-L356 | train | 200,422 |
tanghaibao/jcvi | jcvi/assembly/opticalmap.py | bed | def bed(args):
"""
%prog bed xmlfile
Print summary of optical map alignment in BED format.
"""
from jcvi.formats.bed import sort
p = OptionParser(bed.__doc__)
p.add_option("--blockonly", default=False, action="store_true",
help="Only print out large blocks, not fragments [default: %default]")
p.add_option("--point", default=False, action="store_true",
help="Print accesssion as single point instead of interval")
p.add_option("--scale", type="float",
help="Scale the OM distance by factor")
p.add_option("--switch", default=False, action="store_true",
help="Switch reference and aligned map elements [default: %default]")
p.add_option("--nosort", default=False, action="store_true",
help="Do not sort bed [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
xmlfile, = args
bedfile = xmlfile.rsplit(".", 1)[0] + ".bed"
om = OpticalMap(xmlfile)
om.write_bed(bedfile, point=opts.point, scale=opts.scale,
blockonly=opts.blockonly, switch=opts.switch)
if not opts.nosort:
sort([bedfile, "--inplace"]) | python | def bed(args):
"""
%prog bed xmlfile
Print summary of optical map alignment in BED format.
"""
from jcvi.formats.bed import sort
p = OptionParser(bed.__doc__)
p.add_option("--blockonly", default=False, action="store_true",
help="Only print out large blocks, not fragments [default: %default]")
p.add_option("--point", default=False, action="store_true",
help="Print accesssion as single point instead of interval")
p.add_option("--scale", type="float",
help="Scale the OM distance by factor")
p.add_option("--switch", default=False, action="store_true",
help="Switch reference and aligned map elements [default: %default]")
p.add_option("--nosort", default=False, action="store_true",
help="Do not sort bed [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
xmlfile, = args
bedfile = xmlfile.rsplit(".", 1)[0] + ".bed"
om = OpticalMap(xmlfile)
om.write_bed(bedfile, point=opts.point, scale=opts.scale,
blockonly=opts.blockonly, switch=opts.switch)
if not opts.nosort:
sort([bedfile, "--inplace"]) | [
"def",
"bed",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"sort",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--blockonly\"",
",",
"default",
"=",
"False",
",",
"action",
... | %prog bed xmlfile
Print summary of optical map alignment in BED format. | [
"%prog",
"bed",
"xmlfile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/opticalmap.py#L359-L391 | train | 200,423 |
tanghaibao/jcvi | jcvi/apps/gmap.py | bam | def bam(args):
"""
%prog snp input.gsnap ref.fasta
Convert GSNAP output to BAM.
"""
from jcvi.formats.sizes import Sizes
from jcvi.formats.sam import index
p = OptionParser(bam.__doc__)
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gsnapfile, fastafile = args
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
uniqsam = pf + ".unique.sam"
samstats = uniqsam + ".stats"
sizesfile = Sizes(fastafile).filename
if need_update((gsnapfile, sizesfile), samstats):
cmd = op.join(EYHOME, "gsnap2gff3.pl")
cmd += " --format sam -i {0} -o {1}".format(gsnapfile, uniqsam)
cmd += " -u -l {0} -p {1}".format(sizesfile, opts.cpus)
sh(cmd)
index([uniqsam])
return uniqsam | python | def bam(args):
"""
%prog snp input.gsnap ref.fasta
Convert GSNAP output to BAM.
"""
from jcvi.formats.sizes import Sizes
from jcvi.formats.sam import index
p = OptionParser(bam.__doc__)
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gsnapfile, fastafile = args
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
uniqsam = pf + ".unique.sam"
samstats = uniqsam + ".stats"
sizesfile = Sizes(fastafile).filename
if need_update((gsnapfile, sizesfile), samstats):
cmd = op.join(EYHOME, "gsnap2gff3.pl")
cmd += " --format sam -i {0} -o {1}".format(gsnapfile, uniqsam)
cmd += " -u -l {0} -p {1}".format(sizesfile, opts.cpus)
sh(cmd)
index([uniqsam])
return uniqsam | [
"def",
"bam",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"from",
"jcvi",
".",
"formats",
".",
"sam",
"import",
"index",
"p",
"=",
"OptionParser",
"(",
"bam",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",... | %prog snp input.gsnap ref.fasta
Convert GSNAP output to BAM. | [
"%prog",
"snp",
"input",
".",
"gsnap",
"ref",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/gmap.py#L31-L62 | train | 200,424 |
tanghaibao/jcvi | jcvi/apps/gmap.py | index | def index(args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
p.add_option("--supercat", default=False, action="store_true",
help="Concatenate reference to speed up alignment")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile, supercat=opts.supercat) | python | def index(args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
p.add_option("--supercat", default=False, action="store_true",
help="Concatenate reference to speed up alignment")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile, supercat=opts.supercat) | [
"def",
"index",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"index",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--supercat\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Concatenate referenc... | %prog index database.fasta
`
Wrapper for `gmap_build`. Same interface. | [
"%prog",
"index",
"database",
".",
"fasta",
"Wrapper",
"for",
"gmap_build",
".",
"Same",
"interface",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/gmap.py#L104-L119 | train | 200,425 |
tanghaibao/jcvi | jcvi/apps/gmap.py | gmap | def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile | python | def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile | [
"def",
"gmap",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"gmap",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--cross\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Cross-species alignment\"... | %prog gmap database.fasta fastafile
Wrapper for `gmap`. | [
"%prog",
"gmap",
"database",
".",
"fasta",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/gmap.py#L122-L161 | train | 200,426 |
tanghaibao/jcvi | jcvi/apps/gmap.py | align | def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--native", default=False, action="store_true",
help="Convert GSNAP output to NATIVE format")
p.set_home("eddyyeh")
p.set_outdir()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[:2]
outdir = opts.outdir
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = op.join(outdir, prefix + ".log")
gsnapfile = op.join(outdir, prefix + ".gsnap")
nativefile = gsnapfile.rsplit(".", 1)[0] + ".unique.native"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1"
cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip"
try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.native:
EYHOME = opts.eddyyeh_home
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile | python | def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--native", default=False, action="store_true",
help="Convert GSNAP output to NATIVE format")
p.set_home("eddyyeh")
p.set_outdir()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[:2]
outdir = opts.outdir
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = op.join(outdir, prefix + ".log")
gsnapfile = op.join(outdir, prefix + ".gsnap")
nativefile = gsnapfile.rsplit(".", 1)[0] + ".unique.native"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1"
cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip"
try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.native:
EYHOME = opts.eddyyeh_home
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile | [
"def",
"align",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fastq",
"import",
"guessoffset",
"p",
"=",
"OptionParser",
"(",
"align",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--rnaseq\"",
",",
"default",
"=",
"False",
",",
"... | %prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args. | [
"%prog",
"align",
"database",
".",
"fasta",
"read1",
".",
"fq",
"read2",
".",
"fq"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/gmap.py#L164-L226 | train | 200,427 |
tanghaibao/jcvi | jcvi/compara/quota.py | get_1D_overlap | def get_1D_overlap(eclusters, depth=1):
"""
Find blocks that are 1D overlapping,
returns cliques of block ids that are in conflict
"""
overlap_set = set()
active = set()
ends = []
for i, (chr, left, right) in enumerate(eclusters):
ends.append((chr, left, 0, i)) # 0/1 for left/right-ness
ends.append((chr, right, 1, i))
ends.sort()
chr_last = ""
for chr, pos, left_right, i in ends:
if chr != chr_last:
active.clear()
if left_right == 0:
active.add(i)
else:
active.remove(i)
if len(active) > depth:
overlap_set.add(tuple(sorted(active)))
chr_last = chr
return overlap_set | python | def get_1D_overlap(eclusters, depth=1):
"""
Find blocks that are 1D overlapping,
returns cliques of block ids that are in conflict
"""
overlap_set = set()
active = set()
ends = []
for i, (chr, left, right) in enumerate(eclusters):
ends.append((chr, left, 0, i)) # 0/1 for left/right-ness
ends.append((chr, right, 1, i))
ends.sort()
chr_last = ""
for chr, pos, left_right, i in ends:
if chr != chr_last:
active.clear()
if left_right == 0:
active.add(i)
else:
active.remove(i)
if len(active) > depth:
overlap_set.add(tuple(sorted(active)))
chr_last = chr
return overlap_set | [
"def",
"get_1D_overlap",
"(",
"eclusters",
",",
"depth",
"=",
"1",
")",
":",
"overlap_set",
"=",
"set",
"(",
")",
"active",
"=",
"set",
"(",
")",
"ends",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"chr",
",",
"left",
",",
"right",
")",
"in",
"enumerate... | Find blocks that are 1D overlapping,
returns cliques of block ids that are in conflict | [
"Find",
"blocks",
"that",
"are",
"1D",
"overlapping",
"returns",
"cliques",
"of",
"block",
"ids",
"that",
"are",
"in",
"conflict"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L33-L61 | train | 200,428 |
tanghaibao/jcvi | jcvi/compara/quota.py | make_range | def make_range(clusters, extend=0):
"""
Convert to interval ends from a list of anchors
extend modifies the xmax, ymax boundary of the box,
which can be positive or negative
very useful when we want to make the range as fuzzy as we specify
"""
eclusters = []
for cluster in clusters:
xlist, ylist, scores = zip(*cluster)
score = _score(cluster)
xchr, xmin = min(xlist)
xchr, xmax = max(xlist)
ychr, ymin = min(ylist)
ychr, ymax = max(ylist)
# allow fuzziness to the boundary
xmax += extend
ymax += extend
# because extend can be negative values, we don't want it to be less than min
if xmax < xmin:
xmin, xmax = xmax, xmin
if ymax < ymin:
ymin, ymax = ymax, ymin
eclusters.append(((xchr, xmin, xmax),
(ychr, ymin, ymax), score))
return eclusters | python | def make_range(clusters, extend=0):
"""
Convert to interval ends from a list of anchors
extend modifies the xmax, ymax boundary of the box,
which can be positive or negative
very useful when we want to make the range as fuzzy as we specify
"""
eclusters = []
for cluster in clusters:
xlist, ylist, scores = zip(*cluster)
score = _score(cluster)
xchr, xmin = min(xlist)
xchr, xmax = max(xlist)
ychr, ymin = min(ylist)
ychr, ymax = max(ylist)
# allow fuzziness to the boundary
xmax += extend
ymax += extend
# because extend can be negative values, we don't want it to be less than min
if xmax < xmin:
xmin, xmax = xmax, xmin
if ymax < ymin:
ymin, ymax = ymax, ymin
eclusters.append(((xchr, xmin, xmax),
(ychr, ymin, ymax), score))
return eclusters | [
"def",
"make_range",
"(",
"clusters",
",",
"extend",
"=",
"0",
")",
":",
"eclusters",
"=",
"[",
"]",
"for",
"cluster",
"in",
"clusters",
":",
"xlist",
",",
"ylist",
",",
"scores",
"=",
"zip",
"(",
"*",
"cluster",
")",
"score",
"=",
"_score",
"(",
"... | Convert to interval ends from a list of anchors
extend modifies the xmax, ymax boundary of the box,
which can be positive or negative
very useful when we want to make the range as fuzzy as we specify | [
"Convert",
"to",
"interval",
"ends",
"from",
"a",
"list",
"of",
"anchors",
"extend",
"modifies",
"the",
"xmax",
"ymax",
"boundary",
"of",
"the",
"box",
"which",
"can",
"be",
"positive",
"or",
"negative",
"very",
"useful",
"when",
"we",
"want",
"to",
"make"... | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L102-L131 | train | 200,429 |
tanghaibao/jcvi | jcvi/compara/quota.py | get_constraints | def get_constraints(clusters, quota=(1, 1), Nmax=0):
"""
Check pairwise cluster comparison, if they overlap then mark edge as conflict
"""
qa, qb = quota
eclusters = make_range(clusters, extend=-Nmax)
# (1-based index, cluster score)
nodes = [(i+1, c[-1]) for i, c in enumerate(eclusters)]
eclusters_x, eclusters_y, scores = zip(*eclusters)
# represents the contraints over x-axis and y-axis
constraints_x = get_1D_overlap(eclusters_x, qa)
constraints_y = get_1D_overlap(eclusters_y, qb)
return nodes, constraints_x, constraints_y | python | def get_constraints(clusters, quota=(1, 1), Nmax=0):
"""
Check pairwise cluster comparison, if they overlap then mark edge as conflict
"""
qa, qb = quota
eclusters = make_range(clusters, extend=-Nmax)
# (1-based index, cluster score)
nodes = [(i+1, c[-1]) for i, c in enumerate(eclusters)]
eclusters_x, eclusters_y, scores = zip(*eclusters)
# represents the contraints over x-axis and y-axis
constraints_x = get_1D_overlap(eclusters_x, qa)
constraints_y = get_1D_overlap(eclusters_y, qb)
return nodes, constraints_x, constraints_y | [
"def",
"get_constraints",
"(",
"clusters",
",",
"quota",
"=",
"(",
"1",
",",
"1",
")",
",",
"Nmax",
"=",
"0",
")",
":",
"qa",
",",
"qb",
"=",
"quota",
"eclusters",
"=",
"make_range",
"(",
"clusters",
",",
"extend",
"=",
"-",
"Nmax",
")",
"# (1-base... | Check pairwise cluster comparison, if they overlap then mark edge as conflict | [
"Check",
"pairwise",
"cluster",
"comparison",
"if",
"they",
"overlap",
"then",
"mark",
"edge",
"as",
"conflict"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L134-L149 | train | 200,430 |
tanghaibao/jcvi | jcvi/compara/quota.py | format_lp | def format_lp(nodes, constraints_x, qa, constraints_y, qb):
"""
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
"""
lp_handle = cStringIO.StringIO()
lp_handle.write("Maximize\n ")
records = 0
for i, score in nodes:
lp_handle.write("+ %d x%d " % (score, i))
# SCIP does not like really long string per row
records += 1
if records % 10 == 0:
lp_handle.write("\n")
lp_handle.write("\n")
num_of_constraints = 0
lp_handle.write("Subject To\n")
for c in constraints_x:
additions = " + ".join("x%d" % (x+1) for x in c)
lp_handle.write(" %s <= %d\n" % (additions, qa))
num_of_constraints += len(constraints_x)
# non-self
if not (constraints_x is constraints_y):
for c in constraints_y:
additions = " + ".join("x%d" % (x+1) for x in c)
lp_handle.write(" %s <= %d\n" % (additions, qb))
num_of_constraints += len(constraints_y)
print("number of variables (%d), number of constraints (%d)" %
(len(nodes), num_of_constraints), file=sys.stderr)
lp_handle.write("Binary\n")
for i, score in nodes:
lp_handle.write(" x%d\n" % i)
lp_handle.write("End\n")
lp_data = lp_handle.getvalue()
lp_handle.close()
return lp_data | python | def format_lp(nodes, constraints_x, qa, constraints_y, qb):
"""
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
"""
lp_handle = cStringIO.StringIO()
lp_handle.write("Maximize\n ")
records = 0
for i, score in nodes:
lp_handle.write("+ %d x%d " % (score, i))
# SCIP does not like really long string per row
records += 1
if records % 10 == 0:
lp_handle.write("\n")
lp_handle.write("\n")
num_of_constraints = 0
lp_handle.write("Subject To\n")
for c in constraints_x:
additions = " + ".join("x%d" % (x+1) for x in c)
lp_handle.write(" %s <= %d\n" % (additions, qa))
num_of_constraints += len(constraints_x)
# non-self
if not (constraints_x is constraints_y):
for c in constraints_y:
additions = " + ".join("x%d" % (x+1) for x in c)
lp_handle.write(" %s <= %d\n" % (additions, qb))
num_of_constraints += len(constraints_y)
print("number of variables (%d), number of constraints (%d)" %
(len(nodes), num_of_constraints), file=sys.stderr)
lp_handle.write("Binary\n")
for i, score in nodes:
lp_handle.write(" x%d\n" % i)
lp_handle.write("End\n")
lp_data = lp_handle.getvalue()
lp_handle.close()
return lp_data | [
"def",
"format_lp",
"(",
"nodes",
",",
"constraints_x",
",",
"qa",
",",
"constraints_y",
",",
"qb",
")",
":",
"lp_handle",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"lp_handle",
".",
"write",
"(",
"\"Maximize\\n \"",
")",
"records",
"=",
"0",
"for",
"... | Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End | [
"Maximize",
"4",
"x1",
"+",
"2",
"x2",
"+",
"3",
"x3",
"+",
"x4",
"Subject",
"To",
"x1",
"+",
"x2",
"<",
"=",
"1",
"End"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L152-L198 | train | 200,431 |
tanghaibao/jcvi | jcvi/compara/quota.py | solve_lp | def solve_lp(clusters, quota, work_dir="work", Nmax=0,
self_match=False, solver="SCIP", verbose=False):
"""
Solve the formatted LP instance
"""
qb, qa = quota # flip it
nodes, constraints_x, constraints_y = get_constraints(
clusters, (qa, qb), Nmax=Nmax)
if self_match:
constraints_x = constraints_y = constraints_x | constraints_y
lp_data = format_lp(nodes, constraints_x, qa, constraints_y, qb)
if solver == "SCIP":
filtered_list = SCIPSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("SCIP fails... trying GLPK", file=sys.stderr)
filtered_list = GLPKSolver(
lp_data, work_dir, verbose=verbose).results
elif solver == "GLPK":
filtered_list = GLPKSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("GLPK fails... trying SCIP", file=sys.stderr)
filtered_list = SCIPSolver(
lp_data, work_dir, verbose=verbose).results
return filtered_list | python | def solve_lp(clusters, quota, work_dir="work", Nmax=0,
self_match=False, solver="SCIP", verbose=False):
"""
Solve the formatted LP instance
"""
qb, qa = quota # flip it
nodes, constraints_x, constraints_y = get_constraints(
clusters, (qa, qb), Nmax=Nmax)
if self_match:
constraints_x = constraints_y = constraints_x | constraints_y
lp_data = format_lp(nodes, constraints_x, qa, constraints_y, qb)
if solver == "SCIP":
filtered_list = SCIPSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("SCIP fails... trying GLPK", file=sys.stderr)
filtered_list = GLPKSolver(
lp_data, work_dir, verbose=verbose).results
elif solver == "GLPK":
filtered_list = GLPKSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("GLPK fails... trying SCIP", file=sys.stderr)
filtered_list = SCIPSolver(
lp_data, work_dir, verbose=verbose).results
return filtered_list | [
"def",
"solve_lp",
"(",
"clusters",
",",
"quota",
",",
"work_dir",
"=",
"\"work\"",
",",
"Nmax",
"=",
"0",
",",
"self_match",
"=",
"False",
",",
"solver",
"=",
"\"SCIP\"",
",",
"verbose",
"=",
"False",
")",
":",
"qb",
",",
"qa",
"=",
"quota",
"# flip... | Solve the formatted LP instance | [
"Solve",
"the",
"formatted",
"LP",
"instance"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L201-L229 | train | 200,432 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | print_maps_by_type | def print_maps_by_type(map_type, number=None):
"""
Print all available maps of a given type.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select map type to print.
number : int, optional
Filter output by number of defined colors. By default there is
no numeric filtering.
"""
map_type = map_type.lower().capitalize()
if map_type not in MAP_TYPES:
s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES)
raise ValueError(s)
print(map_type)
map_keys = sorted(COLOR_MAPS[map_type].keys())
format_str = '{0:8} : {1}'
for mk in map_keys:
num_keys = sorted(COLOR_MAPS[map_type][mk].keys(), key=int)
if not number or str(number) in num_keys:
num_str = '{' + ', '.join(num_keys) + '}'
print(format_str.format(mk, num_str)) | python | def print_maps_by_type(map_type, number=None):
"""
Print all available maps of a given type.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select map type to print.
number : int, optional
Filter output by number of defined colors. By default there is
no numeric filtering.
"""
map_type = map_type.lower().capitalize()
if map_type not in MAP_TYPES:
s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES)
raise ValueError(s)
print(map_type)
map_keys = sorted(COLOR_MAPS[map_type].keys())
format_str = '{0:8} : {1}'
for mk in map_keys:
num_keys = sorted(COLOR_MAPS[map_type][mk].keys(), key=int)
if not number or str(number) in num_keys:
num_str = '{' + ', '.join(num_keys) + '}'
print(format_str.format(mk, num_str)) | [
"def",
"print_maps_by_type",
"(",
"map_type",
",",
"number",
"=",
"None",
")",
":",
"map_type",
"=",
"map_type",
".",
"lower",
"(",
")",
".",
"capitalize",
"(",
")",
"if",
"map_type",
"not",
"in",
"MAP_TYPES",
":",
"s",
"=",
"'Invalid map type, must be one o... | Print all available maps of a given type.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select map type to print.
number : int, optional
Filter output by number of defined colors. By default there is
no numeric filtering. | [
"Print",
"all",
"available",
"maps",
"of",
"a",
"given",
"type",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L61-L90 | train | 200,433 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | get_map | def get_map(name, map_type, number, reverse=False):
"""
Return a `BrewerMap` representation of the specified color map.
Parameters
----------
name : str
Name of color map. Use `print_maps` to see available color maps.
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select color map type.
number : int
Number of defined colors in color map.
reverse : bool, optional
Set to True to get the reversed color map.
"""
number = str(number)
map_type = map_type.lower().capitalize()
# check for valid type
if map_type not in MAP_TYPES:
s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES)
raise ValueError(s)
# make a dict of lower case map name to map name so this can be
# insensitive to case.
# this would be a perfect spot for a dict comprehension but going to
# wait on that to preserve 2.6 compatibility.
# map_names = {k.lower(): k for k in COLOR_MAPS[map_type].iterkeys()}
map_names = dict((k.lower(), k) for k in COLOR_MAPS[map_type].keys())
# check for valid name
if name.lower() not in map_names:
s = 'Invalid color map name {0!r} for type {1!r}.\n'
s = s.format(name, map_type)
valid_names = [str(k) for k in COLOR_MAPS[map_type].keys()]
valid_names.sort()
s += 'Valid names are: {0}'.format(valid_names)
raise ValueError(s)
name = map_names[name.lower()]
# check for valid number
if number not in COLOR_MAPS[map_type][name]:
s = 'Invalid number for map type {0!r} and name {1!r}.\n'
s = s.format(map_type, str(name))
valid_numbers = [int(k) for k in COLOR_MAPS[map_type][name].keys()]
valid_numbers.sort()
s += 'Valid numbers are : {0}'.format(valid_numbers)
raise ValueError(s)
colors = COLOR_MAPS[map_type][name][number]['Colors']
if reverse:
name += '_r'
colors = [x for x in reversed(colors)]
return BrewerMap(name, map_type, colors) | python | def get_map(name, map_type, number, reverse=False):
"""
Return a `BrewerMap` representation of the specified color map.
Parameters
----------
name : str
Name of color map. Use `print_maps` to see available color maps.
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select color map type.
number : int
Number of defined colors in color map.
reverse : bool, optional
Set to True to get the reversed color map.
"""
number = str(number)
map_type = map_type.lower().capitalize()
# check for valid type
if map_type not in MAP_TYPES:
s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES)
raise ValueError(s)
# make a dict of lower case map name to map name so this can be
# insensitive to case.
# this would be a perfect spot for a dict comprehension but going to
# wait on that to preserve 2.6 compatibility.
# map_names = {k.lower(): k for k in COLOR_MAPS[map_type].iterkeys()}
map_names = dict((k.lower(), k) for k in COLOR_MAPS[map_type].keys())
# check for valid name
if name.lower() not in map_names:
s = 'Invalid color map name {0!r} for type {1!r}.\n'
s = s.format(name, map_type)
valid_names = [str(k) for k in COLOR_MAPS[map_type].keys()]
valid_names.sort()
s += 'Valid names are: {0}'.format(valid_names)
raise ValueError(s)
name = map_names[name.lower()]
# check for valid number
if number not in COLOR_MAPS[map_type][name]:
s = 'Invalid number for map type {0!r} and name {1!r}.\n'
s = s.format(map_type, str(name))
valid_numbers = [int(k) for k in COLOR_MAPS[map_type][name].keys()]
valid_numbers.sort()
s += 'Valid numbers are : {0}'.format(valid_numbers)
raise ValueError(s)
colors = COLOR_MAPS[map_type][name][number]['Colors']
if reverse:
name += '_r'
colors = [x for x in reversed(colors)]
return BrewerMap(name, map_type, colors) | [
"def",
"get_map",
"(",
"name",
",",
"map_type",
",",
"number",
",",
"reverse",
"=",
"False",
")",
":",
"number",
"=",
"str",
"(",
"number",
")",
"map_type",
"=",
"map_type",
".",
"lower",
"(",
")",
".",
"capitalize",
"(",
")",
"# check for valid type",
... | Return a `BrewerMap` representation of the specified color map.
Parameters
----------
name : str
Name of color map. Use `print_maps` to see available color maps.
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select color map type.
number : int
Number of defined colors in color map.
reverse : bool, optional
Set to True to get the reversed color map. | [
"Return",
"a",
"BrewerMap",
"representation",
"of",
"the",
"specified",
"color",
"map",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L240-L297 | train | 200,434 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | _load_maps_by_type | def _load_maps_by_type(map_type):
"""
Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of defined colors.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Returns
-------
maps : dict of BrewerMap
"""
seq_maps = COLOR_MAPS[map_type]
loaded_maps = {}
for map_name in seq_maps:
loaded_maps[map_name] = {}
for num in seq_maps[map_name]:
inum = int(num)
colors = seq_maps[map_name][num]['Colors']
bmap = BrewerMap(map_name, map_type, colors)
loaded_maps[map_name][inum] = bmap
max_num = int(max(seq_maps[map_name].keys(), key=int))
loaded_maps[map_name]['max'] = loaded_maps[map_name][max_num]
return loaded_maps | python | def _load_maps_by_type(map_type):
"""
Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of defined colors.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Returns
-------
maps : dict of BrewerMap
"""
seq_maps = COLOR_MAPS[map_type]
loaded_maps = {}
for map_name in seq_maps:
loaded_maps[map_name] = {}
for num in seq_maps[map_name]:
inum = int(num)
colors = seq_maps[map_name][num]['Colors']
bmap = BrewerMap(map_name, map_type, colors)
loaded_maps[map_name][inum] = bmap
max_num = int(max(seq_maps[map_name].keys(), key=int))
loaded_maps[map_name]['max'] = loaded_maps[map_name][max_num]
return loaded_maps | [
"def",
"_load_maps_by_type",
"(",
"map_type",
")",
":",
"seq_maps",
"=",
"COLOR_MAPS",
"[",
"map_type",
"]",
"loaded_maps",
"=",
"{",
"}",
"for",
"map_name",
"in",
"seq_maps",
":",
"loaded_maps",
"[",
"map_name",
"]",
"=",
"{",
"}",
"for",
"num",
"in",
"... | Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of defined colors.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Returns
-------
maps : dict of BrewerMap | [
"Load",
"all",
"maps",
"of",
"a",
"given",
"type",
"into",
"a",
"dictionary",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L300-L336 | train | 200,435 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | _ColorMap.mpl_colors | def mpl_colors(self):
"""
Colors expressed on the range 0-1 as used by matplotlib.
"""
mc = []
for color in self.colors:
mc.append(tuple([x / 255. for x in color]))
return mc | python | def mpl_colors(self):
"""
Colors expressed on the range 0-1 as used by matplotlib.
"""
mc = []
for color in self.colors:
mc.append(tuple([x / 255. for x in color]))
return mc | [
"def",
"mpl_colors",
"(",
"self",
")",
":",
"mc",
"=",
"[",
"]",
"for",
"color",
"in",
"self",
".",
"colors",
":",
"mc",
".",
"append",
"(",
"tuple",
"(",
"[",
"x",
"/",
"255.",
"for",
"x",
"in",
"color",
"]",
")",
")",
"return",
"mc"
] | Colors expressed on the range 0-1 as used by matplotlib. | [
"Colors",
"expressed",
"on",
"the",
"range",
"0",
"-",
"1",
"as",
"used",
"by",
"matplotlib",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L140-L150 | train | 200,436 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | _ColorMap.get_mpl_colormap | def get_mpl_colormap(self, **kwargs):
"""
A color map that can be used in matplotlib plots. Requires matplotlib
to be importable. Keyword arguments are passed to
`matplotlib.colors.LinearSegmentedColormap.from_list`.
"""
if not HAVE_MPL: # pragma: no cover
raise RuntimeError('matplotlib not available.')
cmap = LinearSegmentedColormap.from_list(self.name,
self.mpl_colors, **kwargs)
return cmap | python | def get_mpl_colormap(self, **kwargs):
"""
A color map that can be used in matplotlib plots. Requires matplotlib
to be importable. Keyword arguments are passed to
`matplotlib.colors.LinearSegmentedColormap.from_list`.
"""
if not HAVE_MPL: # pragma: no cover
raise RuntimeError('matplotlib not available.')
cmap = LinearSegmentedColormap.from_list(self.name,
self.mpl_colors, **kwargs)
return cmap | [
"def",
"get_mpl_colormap",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"HAVE_MPL",
":",
"# pragma: no cover",
"raise",
"RuntimeError",
"(",
"'matplotlib not available.'",
")",
"cmap",
"=",
"LinearSegmentedColormap",
".",
"from_list",
"(",
"self",
... | A color map that can be used in matplotlib plots. Requires matplotlib
to be importable. Keyword arguments are passed to
`matplotlib.colors.LinearSegmentedColormap.from_list`. | [
"A",
"color",
"map",
"that",
"can",
"be",
"used",
"in",
"matplotlib",
"plots",
".",
"Requires",
"matplotlib",
"to",
"be",
"importable",
".",
"Keyword",
"arguments",
"are",
"passed",
"to",
"matplotlib",
".",
"colors",
".",
"LinearSegmentedColormap",
".",
"from_... | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L161-L174 | train | 200,437 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | _ColorMap.show_as_blocks | def show_as_blocks(self, block_size=100):
"""
Show colors in the IPython Notebook using ipythonblocks.
Parameters
----------
block_size : int, optional
Size of displayed blocks.
"""
from ipythonblocks import BlockGrid
grid = BlockGrid(self.number, 1, block_size=block_size)
for block, color in zip(grid, self.colors):
block.rgb = color
grid.show() | python | def show_as_blocks(self, block_size=100):
"""
Show colors in the IPython Notebook using ipythonblocks.
Parameters
----------
block_size : int, optional
Size of displayed blocks.
"""
from ipythonblocks import BlockGrid
grid = BlockGrid(self.number, 1, block_size=block_size)
for block, color in zip(grid, self.colors):
block.rgb = color
grid.show() | [
"def",
"show_as_blocks",
"(",
"self",
",",
"block_size",
"=",
"100",
")",
":",
"from",
"ipythonblocks",
"import",
"BlockGrid",
"grid",
"=",
"BlockGrid",
"(",
"self",
".",
"number",
",",
"1",
",",
"block_size",
"=",
"block_size",
")",
"for",
"block",
",",
... | Show colors in the IPython Notebook using ipythonblocks.
Parameters
----------
block_size : int, optional
Size of displayed blocks. | [
"Show",
"colors",
"in",
"the",
"IPython",
"Notebook",
"using",
"ipythonblocks",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L176-L193 | train | 200,438 |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | BrewerMap.colorbrewer2_url | def colorbrewer2_url(self):
"""
URL that can be used to view the color map at colorbrewer2.org.
"""
url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}'
return url.format(self.type.lower(), self.name, self.number) | python | def colorbrewer2_url(self):
"""
URL that can be used to view the color map at colorbrewer2.org.
"""
url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}'
return url.format(self.type.lower(), self.name, self.number) | [
"def",
"colorbrewer2_url",
"(",
"self",
")",
":",
"url",
"=",
"'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}'",
"return",
"url",
".",
"format",
"(",
"self",
".",
"type",
".",
"lower",
"(",
")",
",",
"self",
".",
"name",
",",
"self",
".",
"numbe... | URL that can be used to view the color map at colorbrewer2.org. | [
"URL",
"that",
"can",
"be",
"used",
"to",
"view",
"the",
"color",
"map",
"at",
"colorbrewer2",
".",
"org",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L223-L229 | train | 200,439 |
tanghaibao/jcvi | jcvi/formats/chain.py | summary | def summary(args):
"""
%prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file.
"""
from jcvi.formats.fasta import summary as fsummary
from jcvi.utils.cbook import percentage, human_size
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
chainfile, oldfasta, newfasta = args
chain = Chain(chainfile)
ungapped, dt, dq = chain.ungapped, chain.dt, chain.dq
print("File `{0}` contains {1} chains.".\
format(chainfile, len(chain)), file=sys.stderr)
print("ungapped={0} dt={1} dq={2}".\
format(human_size(ungapped), human_size(dt), human_size(dq)), file=sys.stderr)
oldreal, oldnn, oldlen = fsummary([oldfasta, "--outfile=/dev/null"])
print("Old fasta (`{0}`) mapped: {1}".\
format(oldfasta, percentage(ungapped, oldreal)), file=sys.stderr)
newreal, newnn, newlen = fsummary([newfasta, "--outfile=/dev/null"])
print("New fasta (`{0}`) mapped: {1}".\
format(newfasta, percentage(ungapped, newreal)), file=sys.stderr) | python | def summary(args):
"""
%prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file.
"""
from jcvi.formats.fasta import summary as fsummary
from jcvi.utils.cbook import percentage, human_size
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
chainfile, oldfasta, newfasta = args
chain = Chain(chainfile)
ungapped, dt, dq = chain.ungapped, chain.dt, chain.dq
print("File `{0}` contains {1} chains.".\
format(chainfile, len(chain)), file=sys.stderr)
print("ungapped={0} dt={1} dq={2}".\
format(human_size(ungapped), human_size(dt), human_size(dq)), file=sys.stderr)
oldreal, oldnn, oldlen = fsummary([oldfasta, "--outfile=/dev/null"])
print("Old fasta (`{0}`) mapped: {1}".\
format(oldfasta, percentage(ungapped, oldreal)), file=sys.stderr)
newreal, newnn, newlen = fsummary([newfasta, "--outfile=/dev/null"])
print("New fasta (`{0}`) mapped: {1}".\
format(newfasta, percentage(ungapped, newreal)), file=sys.stderr) | [
"def",
"summary",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"summary",
"as",
"fsummary",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"percentage",
",",
"human_size",
"p",
"=",
"OptionParser",
"(",
"summary",
... | %prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file. | [
"%prog",
"summary",
"old",
".",
"new",
".",
"chain",
"old",
".",
"fasta",
"new",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/chain.py#L91-L120 | train | 200,440 |
tanghaibao/jcvi | jcvi/formats/chain.py | fromagp | def fromagp(args):
"""
%prog fromagp agpfile componentfasta objectfasta
Generate chain file from AGP format. The components represent the old
genome (target) and the objects represent new genome (query).
"""
from jcvi.formats.agp import AGP
from jcvi.formats.sizes import Sizes
p = OptionParser(fromagp.__doc__)
p.add_option("--novalidate", default=False, action="store_true",
help="Do not validate AGP")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
agpfile, componentfasta, objectfasta = args
chainfile = agpfile.rsplit(".", 1)[0] + ".chain"
fw = open(chainfile, "w")
agp = AGP(agpfile, validate=(not opts.novalidate))
componentsizes = Sizes(componentfasta).mapping
objectsizes = Sizes(objectfasta).mapping
chain = "chain"
score = 1000
tStrand = "+"
id = 0
for a in agp:
if a.is_gap:
continue
tName = a.component_id
tSize = componentsizes[tName]
tStart = a.component_beg
tEnd = a.component_end
tStart -= 1
qName = a.object
qSize = objectsizes[qName]
qStrand = "-" if a.orientation == "-" else "+"
qStart = a.object_beg
qEnd = a.object_end
if qStrand == '-':
_qStart = qSize - qEnd + 1
_qEnd = qSize - qStart + 1
qStart, qEnd = _qStart, _qEnd
qStart -= 1
id += 1
size = a.object_span
headerline = "\t".join(str(x) for x in (
chain, score, tName, tSize, tStrand, tStart,
tEnd, qName, qSize, qStrand, qStart, qEnd, id
))
alignmentline = size
print(headerline, file=fw)
print(alignmentline, file=fw)
print(file=fw)
fw.close()
logging.debug("File written to `{0}`.".format(chainfile)) | python | def fromagp(args):
"""
%prog fromagp agpfile componentfasta objectfasta
Generate chain file from AGP format. The components represent the old
genome (target) and the objects represent new genome (query).
"""
from jcvi.formats.agp import AGP
from jcvi.formats.sizes import Sizes
p = OptionParser(fromagp.__doc__)
p.add_option("--novalidate", default=False, action="store_true",
help="Do not validate AGP")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
agpfile, componentfasta, objectfasta = args
chainfile = agpfile.rsplit(".", 1)[0] + ".chain"
fw = open(chainfile, "w")
agp = AGP(agpfile, validate=(not opts.novalidate))
componentsizes = Sizes(componentfasta).mapping
objectsizes = Sizes(objectfasta).mapping
chain = "chain"
score = 1000
tStrand = "+"
id = 0
for a in agp:
if a.is_gap:
continue
tName = a.component_id
tSize = componentsizes[tName]
tStart = a.component_beg
tEnd = a.component_end
tStart -= 1
qName = a.object
qSize = objectsizes[qName]
qStrand = "-" if a.orientation == "-" else "+"
qStart = a.object_beg
qEnd = a.object_end
if qStrand == '-':
_qStart = qSize - qEnd + 1
_qEnd = qSize - qStart + 1
qStart, qEnd = _qStart, _qEnd
qStart -= 1
id += 1
size = a.object_span
headerline = "\t".join(str(x) for x in (
chain, score, tName, tSize, tStrand, tStart,
tEnd, qName, qSize, qStrand, qStart, qEnd, id
))
alignmentline = size
print(headerline, file=fw)
print(alignmentline, file=fw)
print(file=fw)
fw.close()
logging.debug("File written to `{0}`.".format(chainfile)) | [
"def",
"fromagp",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"agp",
"import",
"AGP",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"fromagp",
".",
"__doc__",
")",
"p",
".",
"add_option"... | %prog fromagp agpfile componentfasta objectfasta
Generate chain file from AGP format. The components represent the old
genome (target) and the objects represent new genome (query). | [
"%prog",
"fromagp",
"agpfile",
"componentfasta",
"objectfasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/chain.py#L123-L184 | train | 200,441 |
tanghaibao/jcvi | jcvi/formats/chain.py | blat | def blat(args):
"""
%prog blat old.fasta new.fasta
Generate psl file using blat.
"""
p = OptionParser(blat.__doc__)
p.add_option("--minscore", default=100, type="int",
help="Matches minus mismatches gap penalty [default: %default]")
p.add_option("--minid", default=98, type="int",
help="Minimum sequence identity [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
oldfasta, newfasta = args
twobitfiles = []
for fastafile in args:
tbfile = faToTwoBit(fastafile)
twobitfiles.append(tbfile)
oldtwobit, newtwobit = twobitfiles
cmd = "pblat -threads={0}".format(opts.cpus) if which("pblat") else "blat"
cmd += " {0} {1}".format(oldtwobit, newfasta)
cmd += " -tileSize=12 -minScore={0} -minIdentity={1} ".\
format(opts.minscore, opts.minid)
pslfile = "{0}.{1}.psl".format(*(op.basename(x).split('.')[0] \
for x in (newfasta, oldfasta)))
cmd += pslfile
sh(cmd) | python | def blat(args):
"""
%prog blat old.fasta new.fasta
Generate psl file using blat.
"""
p = OptionParser(blat.__doc__)
p.add_option("--minscore", default=100, type="int",
help="Matches minus mismatches gap penalty [default: %default]")
p.add_option("--minid", default=98, type="int",
help="Minimum sequence identity [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
oldfasta, newfasta = args
twobitfiles = []
for fastafile in args:
tbfile = faToTwoBit(fastafile)
twobitfiles.append(tbfile)
oldtwobit, newtwobit = twobitfiles
cmd = "pblat -threads={0}".format(opts.cpus) if which("pblat") else "blat"
cmd += " {0} {1}".format(oldtwobit, newfasta)
cmd += " -tileSize=12 -minScore={0} -minIdentity={1} ".\
format(opts.minscore, opts.minid)
pslfile = "{0}.{1}.psl".format(*(op.basename(x).split('.')[0] \
for x in (newfasta, oldfasta)))
cmd += pslfile
sh(cmd) | [
"def",
"blat",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"blat",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--minscore\"",
",",
"default",
"=",
"100",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Matches minus mismatches gap pena... | %prog blat old.fasta new.fasta
Generate psl file using blat. | [
"%prog",
"blat",
"old",
".",
"fasta",
"new",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/chain.py#L195-L226 | train | 200,442 |
tanghaibao/jcvi | jcvi/formats/chain.py | frompsl | def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
pslfile, oldfasta, newfasta = args
pf = oldfasta.split(".")[0]
# Chain together alignments from using axtChain
chainfile = pf + ".chain"
twobitfiles = []
for fastafile in (oldfasta, newfasta):
tbfile = faToTwoBit(fastafile)
twobitfiles.append(tbfile)
oldtwobit, newtwobit = twobitfiles
if need_update(pslfile, chainfile):
cmd = "axtChain -linearGap=medium -psl {0}".format(pslfile)
cmd += " {0} {1} {2}".format(oldtwobit, newtwobit, chainfile)
sh(cmd)
# Sort chain files
sortedchain = chainfile.rsplit(".", 1)[0] + ".sorted.chain"
if need_update(chainfile, sortedchain):
cmd = "chainSort {0} {1}".format(chainfile, sortedchain)
sh(cmd)
# Make alignment nets from chains
netfile = pf + ".net"
oldsizes = Sizes(oldfasta).filename
newsizes = Sizes(newfasta).filename
if need_update((sortedchain, oldsizes, newsizes), netfile):
cmd = "chainNet {0} {1} {2}".format(sortedchain, oldsizes, newsizes)
cmd += " {0} /dev/null".format(netfile)
sh(cmd)
# Create liftOver chain file
liftoverfile = pf + ".liftover.chain"
if need_update((netfile, sortedchain), liftoverfile):
cmd = "netChainSubset {0} {1} {2}".\
format(netfile, sortedchain, liftoverfile)
sh(cmd) | python | def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
pslfile, oldfasta, newfasta = args
pf = oldfasta.split(".")[0]
# Chain together alignments from using axtChain
chainfile = pf + ".chain"
twobitfiles = []
for fastafile in (oldfasta, newfasta):
tbfile = faToTwoBit(fastafile)
twobitfiles.append(tbfile)
oldtwobit, newtwobit = twobitfiles
if need_update(pslfile, chainfile):
cmd = "axtChain -linearGap=medium -psl {0}".format(pslfile)
cmd += " {0} {1} {2}".format(oldtwobit, newtwobit, chainfile)
sh(cmd)
# Sort chain files
sortedchain = chainfile.rsplit(".", 1)[0] + ".sorted.chain"
if need_update(chainfile, sortedchain):
cmd = "chainSort {0} {1}".format(chainfile, sortedchain)
sh(cmd)
# Make alignment nets from chains
netfile = pf + ".net"
oldsizes = Sizes(oldfasta).filename
newsizes = Sizes(newfasta).filename
if need_update((sortedchain, oldsizes, newsizes), netfile):
cmd = "chainNet {0} {1} {2}".format(sortedchain, oldsizes, newsizes)
cmd += " {0} /dev/null".format(netfile)
sh(cmd)
# Create liftOver chain file
liftoverfile = pf + ".liftover.chain"
if need_update((netfile, sortedchain), liftoverfile):
cmd = "netChainSubset {0} {1} {2}".\
format(netfile, sortedchain, liftoverfile)
sh(cmd) | [
"def",
"frompsl",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"frompsl",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | %prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver> | [
"%prog",
"frompsl",
"old",
".",
"new",
".",
"psl",
"old",
".",
"fasta",
"new",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/chain.py#L229-L280 | train | 200,443 |
tanghaibao/jcvi | jcvi/apps/lastz.py | lastz_to_blast | def lastz_to_blast(row):
"""
Convert the lastz tabular to the blast tabular, see headers above
Obsolete after LASTZ version 1.02.40
"""
atoms = row.strip().split("\t")
name1, name2, coverage, identity, nmismatch, ngap, \
start1, end1, strand1, start2, end2, strand2, score = atoms
identity = identity.replace("%", "")
hitlen = coverage.split("/")[1]
score = float(score)
same_strand = (strand1 == strand2)
if not same_strand:
start2, end2 = end2, start2
evalue = blastz_score_to_ncbi_expectation(score)
score = blastz_score_to_ncbi_bits(score)
evalue, score = "%.2g" % evalue, "%.1f" % score
return "\t".join((name1, name2, identity, hitlen, nmismatch, ngap, \
start1, end1, start2, end2, evalue, score)) | python | def lastz_to_blast(row):
"""
Convert the lastz tabular to the blast tabular, see headers above
Obsolete after LASTZ version 1.02.40
"""
atoms = row.strip().split("\t")
name1, name2, coverage, identity, nmismatch, ngap, \
start1, end1, strand1, start2, end2, strand2, score = atoms
identity = identity.replace("%", "")
hitlen = coverage.split("/")[1]
score = float(score)
same_strand = (strand1 == strand2)
if not same_strand:
start2, end2 = end2, start2
evalue = blastz_score_to_ncbi_expectation(score)
score = blastz_score_to_ncbi_bits(score)
evalue, score = "%.2g" % evalue, "%.1f" % score
return "\t".join((name1, name2, identity, hitlen, nmismatch, ngap, \
start1, end1, start2, end2, evalue, score)) | [
"def",
"lastz_to_blast",
"(",
"row",
")",
":",
"atoms",
"=",
"row",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"name1",
",",
"name2",
",",
"coverage",
",",
"identity",
",",
"nmismatch",
",",
"ngap",
",",
"start1",
",",
"end1",
",",
... | Convert the lastz tabular to the blast tabular, see headers above
Obsolete after LASTZ version 1.02.40 | [
"Convert",
"the",
"lastz",
"tabular",
"to",
"the",
"blast",
"tabular",
"see",
"headers",
"above",
"Obsolete",
"after",
"LASTZ",
"version",
"1",
".",
"02",
".",
"40"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/lastz.py#L47-L66 | train | 200,444 |
tanghaibao/jcvi | jcvi/apps/lastz.py | lastz_2bit | def lastz_2bit(t):
"""
Used for formats other than BLAST, i.e. lav, maf, etc. which requires the
database file to contain a single FASTA record.
"""
bfasta_fn, afasta_fn, outfile, lastz_bin, extra, mask, format = t
ref_tags = [Darkspace]
qry_tags = [Darkspace]
ref_tags, qry_tags = add_mask(ref_tags, qry_tags, mask=mask)
lastz_cmd = Lastz_template.format(lastz_bin, bfasta_fn, ref_tags, \
afasta_fn, qry_tags)
if extra:
lastz_cmd += " " + extra.strip()
lastz_cmd += " --format={0}".format(format)
proc = Popen(lastz_cmd)
out_fh = open(outfile, "w")
logging.debug("job <%d> started: %s" % (proc.pid, lastz_cmd))
for row in proc.stdout:
out_fh.write(row)
out_fh.flush()
logging.debug("job <%d> finished" % proc.pid) | python | def lastz_2bit(t):
"""
Used for formats other than BLAST, i.e. lav, maf, etc. which requires the
database file to contain a single FASTA record.
"""
bfasta_fn, afasta_fn, outfile, lastz_bin, extra, mask, format = t
ref_tags = [Darkspace]
qry_tags = [Darkspace]
ref_tags, qry_tags = add_mask(ref_tags, qry_tags, mask=mask)
lastz_cmd = Lastz_template.format(lastz_bin, bfasta_fn, ref_tags, \
afasta_fn, qry_tags)
if extra:
lastz_cmd += " " + extra.strip()
lastz_cmd += " --format={0}".format(format)
proc = Popen(lastz_cmd)
out_fh = open(outfile, "w")
logging.debug("job <%d> started: %s" % (proc.pid, lastz_cmd))
for row in proc.stdout:
out_fh.write(row)
out_fh.flush()
logging.debug("job <%d> finished" % proc.pid) | [
"def",
"lastz_2bit",
"(",
"t",
")",
":",
"bfasta_fn",
",",
"afasta_fn",
",",
"outfile",
",",
"lastz_bin",
",",
"extra",
",",
"mask",
",",
"format",
"=",
"t",
"ref_tags",
"=",
"[",
"Darkspace",
"]",
"qry_tags",
"=",
"[",
"Darkspace",
"]",
"ref_tags",
",... | Used for formats other than BLAST, i.e. lav, maf, etc. which requires the
database file to contain a single FASTA record. | [
"Used",
"for",
"formats",
"other",
"than",
"BLAST",
"i",
".",
"e",
".",
"lav",
"maf",
"etc",
".",
"which",
"requires",
"the",
"database",
"file",
"to",
"contain",
"a",
"single",
"FASTA",
"record",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/lastz.py#L80-L104 | train | 200,445 |
tanghaibao/jcvi | jcvi/annotation/automaton.py | augustus | def augustus(args):
"""
%prog augustus fastafile
Run parallel AUGUSTUS. Final results can be reformatted using
annotation.reformat.augustus().
"""
p = OptionParser(augustus.__doc__)
p.add_option("--species", default="maize",
help="Use species model for prediction")
p.add_option("--hintsfile", help="Hint-guided AUGUSTUS")
p.add_option("--nogff3", default=False, action="store_true",
help="Turn --gff3=off")
p.set_home("augustus")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
cpus = opts.cpus
mhome = opts.augustus_home
gff3 = not opts.nogff3
suffix = ".gff3" if gff3 else ".out"
cfgfile = op.join(mhome, "config/extrinsic/extrinsic.M.RM.E.W.cfg")
outdir = mkdtemp(dir=".")
fs = split([fastafile, outdir, str(cpus)])
augustuswrap_params = partial(augustuswrap, species=opts.species,
gff3=gff3, cfgfile=cfgfile,
hintsfile=opts.hintsfile)
g = Jobs(augustuswrap_params, fs.names)
g.run()
gff3files = [x.rsplit(".", 1)[0] + suffix for x in fs.names]
outfile = fastafile.rsplit(".", 1)[0] + suffix
FileMerger(gff3files, outfile=outfile).merge()
shutil.rmtree(outdir)
if gff3:
from jcvi.annotation.reformat import augustus as reformat_augustus
reformat_outfile = outfile.replace(".gff3", ".reformat.gff3")
reformat_augustus([outfile, "--outfile={0}".format(reformat_outfile)]) | python | def augustus(args):
"""
%prog augustus fastafile
Run parallel AUGUSTUS. Final results can be reformatted using
annotation.reformat.augustus().
"""
p = OptionParser(augustus.__doc__)
p.add_option("--species", default="maize",
help="Use species model for prediction")
p.add_option("--hintsfile", help="Hint-guided AUGUSTUS")
p.add_option("--nogff3", default=False, action="store_true",
help="Turn --gff3=off")
p.set_home("augustus")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
cpus = opts.cpus
mhome = opts.augustus_home
gff3 = not opts.nogff3
suffix = ".gff3" if gff3 else ".out"
cfgfile = op.join(mhome, "config/extrinsic/extrinsic.M.RM.E.W.cfg")
outdir = mkdtemp(dir=".")
fs = split([fastafile, outdir, str(cpus)])
augustuswrap_params = partial(augustuswrap, species=opts.species,
gff3=gff3, cfgfile=cfgfile,
hintsfile=opts.hintsfile)
g = Jobs(augustuswrap_params, fs.names)
g.run()
gff3files = [x.rsplit(".", 1)[0] + suffix for x in fs.names]
outfile = fastafile.rsplit(".", 1)[0] + suffix
FileMerger(gff3files, outfile=outfile).merge()
shutil.rmtree(outdir)
if gff3:
from jcvi.annotation.reformat import augustus as reformat_augustus
reformat_outfile = outfile.replace(".gff3", ".reformat.gff3")
reformat_augustus([outfile, "--outfile={0}".format(reformat_outfile)]) | [
"def",
"augustus",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"augustus",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--species\"",
",",
"default",
"=",
"\"maize\"",
",",
"help",
"=",
"\"Use species model for prediction\"",
")",
"p",
".",... | %prog augustus fastafile
Run parallel AUGUSTUS. Final results can be reformatted using
annotation.reformat.augustus(). | [
"%prog",
"augustus",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/automaton.py#L53-L97 | train | 200,446 |
tanghaibao/jcvi | jcvi/annotation/automaton.py | star | def star(args):
"""
%prog star folder reference
Run star on a folder with reads.
"""
p = OptionParser(star.__doc__)
p.add_option("--single", default=False, action="store_true",
help="Single end mapping")
p.set_fastq_names()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
folder, reference = args
cpus = opts.cpus
mm = MakeManager()
num = 1 if opts.single else 2
folder, reference = args
gd = "GenomeDir"
mkdir(gd)
STAR = "STAR --runThreadN {0} --genomeDir {1}".format(cpus, gd)
# Step 0: build genome index
genomeidx = op.join(gd, "Genome")
if need_update(reference, genomeidx):
cmd = STAR + " --runMode genomeGenerate"
cmd += " --genomeFastaFiles {0}".format(reference)
mm.add(reference, genomeidx, cmd)
# Step 1: align
for p, prefix in iter_project(folder, opts.names, num):
pf = "{0}_star".format(prefix)
bamfile = pf + "Aligned.sortedByCoord.out.bam"
cmd = STAR + " --readFilesIn {0}".format(" ".join(p))
if p[0].endswith(".gz"):
cmd += " --readFilesCommand zcat"
cmd += " --outSAMtype BAM SortedByCoordinate"
cmd += " --outFileNamePrefix {0}".format(pf)
cmd += " --twopassMode Basic"
# Compatibility for cufflinks
cmd += " --outSAMstrandField intronMotif"
cmd += " --outFilterIntronMotifs RemoveNoncanonical"
mm.add(p, bamfile, cmd)
mm.write() | python | def star(args):
"""
%prog star folder reference
Run star on a folder with reads.
"""
p = OptionParser(star.__doc__)
p.add_option("--single", default=False, action="store_true",
help="Single end mapping")
p.set_fastq_names()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
folder, reference = args
cpus = opts.cpus
mm = MakeManager()
num = 1 if opts.single else 2
folder, reference = args
gd = "GenomeDir"
mkdir(gd)
STAR = "STAR --runThreadN {0} --genomeDir {1}".format(cpus, gd)
# Step 0: build genome index
genomeidx = op.join(gd, "Genome")
if need_update(reference, genomeidx):
cmd = STAR + " --runMode genomeGenerate"
cmd += " --genomeFastaFiles {0}".format(reference)
mm.add(reference, genomeidx, cmd)
# Step 1: align
for p, prefix in iter_project(folder, opts.names, num):
pf = "{0}_star".format(prefix)
bamfile = pf + "Aligned.sortedByCoord.out.bam"
cmd = STAR + " --readFilesIn {0}".format(" ".join(p))
if p[0].endswith(".gz"):
cmd += " --readFilesCommand zcat"
cmd += " --outSAMtype BAM SortedByCoordinate"
cmd += " --outFileNamePrefix {0}".format(pf)
cmd += " --twopassMode Basic"
# Compatibility for cufflinks
cmd += " --outSAMstrandField intronMotif"
cmd += " --outFilterIntronMotifs RemoveNoncanonical"
mm.add(p, bamfile, cmd)
mm.write() | [
"def",
"star",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"star",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--single\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Single end mapping\"",
... | %prog star folder reference
Run star on a folder with reads. | [
"%prog",
"star",
"folder",
"reference"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/automaton.py#L100-L148 | train | 200,447 |
tanghaibao/jcvi | jcvi/annotation/automaton.py | cufflinks | def cufflinks(args):
"""
%prog cufflinks folder reference
Run cufflinks on a folder containing tophat results.
"""
p = OptionParser(cufflinks.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
folder, reference = args
cpus = opts.cpus
gtf = opts.gtf
transcripts = "transcripts.gtf"
mm = MakeManager()
gtfs = []
for bam in iglob(folder, "*.bam"):
pf = op.basename(bam).split(".")[0]
outdir = pf + "_cufflinks"
cmd = "cufflinks"
cmd += " -o {0}".format(outdir)
cmd += " -p {0}".format(cpus)
if gtf:
cmd += " -g {0}".format(gtf)
cmd += " --frag-bias-correct {0}".format(reference)
cmd += " --multi-read-correct"
cmd += " {0}".format(bam)
cgtf = op.join(outdir, transcripts)
mm.add(bam, cgtf, cmd)
gtfs.append(cgtf)
assemblylist = "assembly_list.txt"
cmd = 'find . -name "{0}" > {1}'.format(transcripts, assemblylist)
mm.add(gtfs, assemblylist, cmd)
mergedgtf = "merged/merged.gtf"
cmd = "cuffmerge"
cmd += " -o merged"
cmd += " -p {0}".format(cpus)
if gtf:
cmd += " -g {0}".format(gtf)
cmd += " -s {0}".format(reference)
cmd += " {0}".format(assemblylist)
mm.add(assemblylist, mergedgtf, cmd)
mm.write() | python | def cufflinks(args):
"""
%prog cufflinks folder reference
Run cufflinks on a folder containing tophat results.
"""
p = OptionParser(cufflinks.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
folder, reference = args
cpus = opts.cpus
gtf = opts.gtf
transcripts = "transcripts.gtf"
mm = MakeManager()
gtfs = []
for bam in iglob(folder, "*.bam"):
pf = op.basename(bam).split(".")[0]
outdir = pf + "_cufflinks"
cmd = "cufflinks"
cmd += " -o {0}".format(outdir)
cmd += " -p {0}".format(cpus)
if gtf:
cmd += " -g {0}".format(gtf)
cmd += " --frag-bias-correct {0}".format(reference)
cmd += " --multi-read-correct"
cmd += " {0}".format(bam)
cgtf = op.join(outdir, transcripts)
mm.add(bam, cgtf, cmd)
gtfs.append(cgtf)
assemblylist = "assembly_list.txt"
cmd = 'find . -name "{0}" > {1}'.format(transcripts, assemblylist)
mm.add(gtfs, assemblylist, cmd)
mergedgtf = "merged/merged.gtf"
cmd = "cuffmerge"
cmd += " -o merged"
cmd += " -p {0}".format(cpus)
if gtf:
cmd += " -g {0}".format(gtf)
cmd += " -s {0}".format(reference)
cmd += " {0}".format(assemblylist)
mm.add(assemblylist, mergedgtf, cmd)
mm.write() | [
"def",
"cufflinks",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"cufflinks",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gtf\"",
",",
"help",
"=",
"\"Reference annotation [default: %default]\"",
")",
"p",
".",
"set_cpus",
"(",
")",
"opts... | %prog cufflinks folder reference
Run cufflinks on a folder containing tophat results. | [
"%prog",
"cufflinks",
"folder",
"reference"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/automaton.py#L151-L201 | train | 200,448 |
tanghaibao/jcvi | jcvi/annotation/automaton.py | tophat | def tophat(args):
"""
%prog tophat folder reference
Run tophat on a folder of reads.
"""
from jcvi.apps.bowtie import check_index
from jcvi.formats.fastq import guessoffset
p = OptionParser(tophat.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.add_option("--single", default=False, action="store_true",
help="Single end mapping")
p.add_option("--intron", default=15000, type="int",
help="Max intron size [default: %default]")
p.add_option("--dist", default=-50, type="int",
help="Mate inner distance [default: %default]")
p.add_option("--stdev", default=50, type="int",
help="Mate standard deviation [default: %default]")
p.set_phred()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
num = 1 if opts.single else 2
folder, reference = args
reference = check_index(reference)
for p, prefix in iter_project(folder, n=num):
outdir = "{0}_tophat".format(prefix)
outfile = op.join(outdir, "accepted_hits.bam")
if op.exists(outfile):
logging.debug("File `{0}` found. Skipping.".format(outfile))
continue
cmd = "tophat -p {0}".format(opts.cpus)
if opts.gtf:
cmd += " -G {0}".format(opts.gtf)
cmd += " -o {0}".format(outdir)
if num == 1: # Single-end
a, = p
else: # Paired-end
a, b = p
cmd += " --max-intron-length {0}".format(opts.intron)
cmd += " --mate-inner-dist {0}".format(opts.dist)
cmd += " --mate-std-dev {0}".format(opts.stdev)
phred = opts.phred or str(guessoffset([a]))
if phred == "64":
cmd += " --phred64-quals"
cmd += " {0} {1}".format(reference, " ".join(p))
sh(cmd) | python | def tophat(args):
"""
%prog tophat folder reference
Run tophat on a folder of reads.
"""
from jcvi.apps.bowtie import check_index
from jcvi.formats.fastq import guessoffset
p = OptionParser(tophat.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.add_option("--single", default=False, action="store_true",
help="Single end mapping")
p.add_option("--intron", default=15000, type="int",
help="Max intron size [default: %default]")
p.add_option("--dist", default=-50, type="int",
help="Mate inner distance [default: %default]")
p.add_option("--stdev", default=50, type="int",
help="Mate standard deviation [default: %default]")
p.set_phred()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
num = 1 if opts.single else 2
folder, reference = args
reference = check_index(reference)
for p, prefix in iter_project(folder, n=num):
outdir = "{0}_tophat".format(prefix)
outfile = op.join(outdir, "accepted_hits.bam")
if op.exists(outfile):
logging.debug("File `{0}` found. Skipping.".format(outfile))
continue
cmd = "tophat -p {0}".format(opts.cpus)
if opts.gtf:
cmd += " -G {0}".format(opts.gtf)
cmd += " -o {0}".format(outdir)
if num == 1: # Single-end
a, = p
else: # Paired-end
a, b = p
cmd += " --max-intron-length {0}".format(opts.intron)
cmd += " --mate-inner-dist {0}".format(opts.dist)
cmd += " --mate-std-dev {0}".format(opts.stdev)
phred = opts.phred or str(guessoffset([a]))
if phred == "64":
cmd += " --phred64-quals"
cmd += " {0} {1}".format(reference, " ".join(p))
sh(cmd) | [
"def",
"tophat",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"bowtie",
"import",
"check_index",
"from",
"jcvi",
".",
"formats",
".",
"fastq",
"import",
"guessoffset",
"p",
"=",
"OptionParser",
"(",
"tophat",
".",
"__doc__",
")",
"p",
".",
... | %prog tophat folder reference
Run tophat on a folder of reads. | [
"%prog",
"tophat",
"folder",
"reference"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/automaton.py#L204-L258 | train | 200,449 |
tanghaibao/jcvi | jcvi/assembly/hic.py | hmean_int | def hmean_int(a, a_min=5778, a_max=1149851):
""" Harmonic mean of an array, returns the closest int
"""
from scipy.stats import hmean
return int(round(hmean(np.clip(a, a_min, a_max)))) | python | def hmean_int(a, a_min=5778, a_max=1149851):
""" Harmonic mean of an array, returns the closest int
"""
from scipy.stats import hmean
return int(round(hmean(np.clip(a, a_min, a_max)))) | [
"def",
"hmean_int",
"(",
"a",
",",
"a_min",
"=",
"5778",
",",
"a_max",
"=",
"1149851",
")",
":",
"from",
"scipy",
".",
"stats",
"import",
"hmean",
"return",
"int",
"(",
"round",
"(",
"hmean",
"(",
"np",
".",
"clip",
"(",
"a",
",",
"a_min",
",",
"... | Harmonic mean of an array, returns the closest int | [
"Harmonic",
"mean",
"of",
"an",
"array",
"returns",
"the",
"closest",
"int"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L490-L494 | train | 200,450 |
tanghaibao/jcvi | jcvi/assembly/hic.py | golden_array | def golden_array(a, phi=1.61803398875, lb=LB, ub=UB):
""" Given list of ints, we aggregate similar values so that it becomes an
array of multiples of phi, where phi is the golden ratio.
phi ^ 14 = 843
phi ^ 33 = 7881196
So the array of counts go between 843 to 788196. One triva is that the
exponents of phi gets closer to integers as N grows. See interesting
discussion here:
<https://www.johndcook.com/blog/2017/03/22/golden-powers-are-nearly-integers/>
"""
counts = np.zeros(BB, dtype=int)
for x in a:
c = int(round(math.log(x, phi)))
if c < lb:
c = lb
if c > ub:
c = ub
counts[c - lb] += 1
return counts | python | def golden_array(a, phi=1.61803398875, lb=LB, ub=UB):
""" Given list of ints, we aggregate similar values so that it becomes an
array of multiples of phi, where phi is the golden ratio.
phi ^ 14 = 843
phi ^ 33 = 7881196
So the array of counts go between 843 to 788196. One triva is that the
exponents of phi gets closer to integers as N grows. See interesting
discussion here:
<https://www.johndcook.com/blog/2017/03/22/golden-powers-are-nearly-integers/>
"""
counts = np.zeros(BB, dtype=int)
for x in a:
c = int(round(math.log(x, phi)))
if c < lb:
c = lb
if c > ub:
c = ub
counts[c - lb] += 1
return counts | [
"def",
"golden_array",
"(",
"a",
",",
"phi",
"=",
"1.61803398875",
",",
"lb",
"=",
"LB",
",",
"ub",
"=",
"UB",
")",
":",
"counts",
"=",
"np",
".",
"zeros",
"(",
"BB",
",",
"dtype",
"=",
"int",
")",
"for",
"x",
"in",
"a",
":",
"c",
"=",
"int",... | Given list of ints, we aggregate similar values so that it becomes an
array of multiples of phi, where phi is the golden ratio.
phi ^ 14 = 843
phi ^ 33 = 7881196
So the array of counts go between 843 to 788196. One triva is that the
exponents of phi gets closer to integers as N grows. See interesting
discussion here:
<https://www.johndcook.com/blog/2017/03/22/golden-powers-are-nearly-integers/> | [
"Given",
"list",
"of",
"ints",
"we",
"aggregate",
"similar",
"values",
"so",
"that",
"it",
"becomes",
"an",
"array",
"of",
"multiples",
"of",
"phi",
"where",
"phi",
"is",
"the",
"golden",
"ratio",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L497-L517 | train | 200,451 |
tanghaibao/jcvi | jcvi/assembly/hic.py | heatmap | def heatmap(args):
"""
%prog heatmap input.npy genome.json
Plot heatmap based on .npy data file. The .npy stores a square matrix with
bins of genome, and cells inside the matrix represent number of links
between bin i and bin j. The `genome.json` contains the offsets of each
contig/chr so that we know where to draw boundary lines, or extract per
contig/chromosome heatmap.
"""
p = OptionParser(heatmap.__doc__)
p.add_option("--resolution", default=500000, type="int",
help="Resolution when counting the links")
p.add_option("--chr", help="Plot this contig/chr only")
p.add_option("--nobreaks", default=False, action="store_true",
help="Do not plot breaks (esp. if contigs are small)")
opts, args, iopts = p.set_image_options(args, figsize="10x10",
style="white", cmap="coolwarm",
format="png", dpi=120)
if len(args) != 2:
sys.exit(not p.print_help())
npyfile, jsonfile = args
contig = opts.chr
# Load contig/chromosome starts and sizes
header = json.loads(open(jsonfile).read())
resolution = header.get("resolution", opts.resolution)
logging.debug("Resolution set to {}".format(resolution))
# Load the matrix
A = np.load(npyfile)
# Select specific submatrix
if contig:
contig_start = header["starts"][contig]
contig_size = header["sizes"][contig]
contig_end = contig_start + contig_size
A = A[contig_start: contig_end, contig_start: contig_end]
# Several concerns in practice:
# The diagonal counts may be too strong, this can either be resolved by
# masking them. Or perform a log transform on the entire heatmap.
B = A.astype("float64")
B += 1.0
B = np.log(B)
vmin, vmax = 1, 7
B[B < vmin] = vmin
B[B > vmax] = vmax
print(B)
logging.debug("Matrix log-transformation and thresholding ({}-{}) done"
.format(vmin, vmax))
# Canvas
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1]) # whole canvas
ax = fig.add_axes([.05, .05, .9, .9]) # just the heatmap
breaks = header["starts"].values()
breaks += [header["total_bins"]] # This is actually discarded
breaks = sorted(breaks)[1:]
if contig or opts.nobreaks:
breaks = []
plot_heatmap(ax, B, breaks, iopts, binsize=resolution)
# Title
pf = npyfile.rsplit(".", 1)[0]
title = pf
if contig:
title += "-{}".format(contig)
root.text(.5, .98, title, color="darkslategray", size=18,
ha="center", va="center")
normalize_axes(root)
image_name = title + "." + iopts.format
# macOS sometimes has way too verbose output
logging.getLogger().setLevel(logging.CRITICAL)
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | python | def heatmap(args):
"""
%prog heatmap input.npy genome.json
Plot heatmap based on .npy data file. The .npy stores a square matrix with
bins of genome, and cells inside the matrix represent number of links
between bin i and bin j. The `genome.json` contains the offsets of each
contig/chr so that we know where to draw boundary lines, or extract per
contig/chromosome heatmap.
"""
p = OptionParser(heatmap.__doc__)
p.add_option("--resolution", default=500000, type="int",
help="Resolution when counting the links")
p.add_option("--chr", help="Plot this contig/chr only")
p.add_option("--nobreaks", default=False, action="store_true",
help="Do not plot breaks (esp. if contigs are small)")
opts, args, iopts = p.set_image_options(args, figsize="10x10",
style="white", cmap="coolwarm",
format="png", dpi=120)
if len(args) != 2:
sys.exit(not p.print_help())
npyfile, jsonfile = args
contig = opts.chr
# Load contig/chromosome starts and sizes
header = json.loads(open(jsonfile).read())
resolution = header.get("resolution", opts.resolution)
logging.debug("Resolution set to {}".format(resolution))
# Load the matrix
A = np.load(npyfile)
# Select specific submatrix
if contig:
contig_start = header["starts"][contig]
contig_size = header["sizes"][contig]
contig_end = contig_start + contig_size
A = A[contig_start: contig_end, contig_start: contig_end]
# Several concerns in practice:
# The diagonal counts may be too strong, this can either be resolved by
# masking them. Or perform a log transform on the entire heatmap.
B = A.astype("float64")
B += 1.0
B = np.log(B)
vmin, vmax = 1, 7
B[B < vmin] = vmin
B[B > vmax] = vmax
print(B)
logging.debug("Matrix log-transformation and thresholding ({}-{}) done"
.format(vmin, vmax))
# Canvas
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1]) # whole canvas
ax = fig.add_axes([.05, .05, .9, .9]) # just the heatmap
breaks = header["starts"].values()
breaks += [header["total_bins"]] # This is actually discarded
breaks = sorted(breaks)[1:]
if contig or opts.nobreaks:
breaks = []
plot_heatmap(ax, B, breaks, iopts, binsize=resolution)
# Title
pf = npyfile.rsplit(".", 1)[0]
title = pf
if contig:
title += "-{}".format(contig)
root.text(.5, .98, title, color="darkslategray", size=18,
ha="center", va="center")
normalize_axes(root)
image_name = title + "." + iopts.format
# macOS sometimes has way too verbose output
logging.getLogger().setLevel(logging.CRITICAL)
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | [
"def",
"heatmap",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"heatmap",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--resolution\"",
",",
"default",
"=",
"500000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Resolution when counti... | %prog heatmap input.npy genome.json
Plot heatmap based on .npy data file. The .npy stores a square matrix with
bins of genome, and cells inside the matrix represent number of links
between bin i and bin j. The `genome.json` contains the offsets of each
contig/chr so that we know where to draw boundary lines, or extract per
contig/chromosome heatmap. | [
"%prog",
"heatmap",
"input",
".",
"npy",
"genome",
".",
"json"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L555-L631 | train | 200,452 |
tanghaibao/jcvi | jcvi/assembly/hic.py | get_seqstarts | def get_seqstarts(bamfile, N):
""" Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells
"""
import pysam
bamfile = pysam.AlignmentFile(bamfile, "rb")
seqsize = {}
for kv in bamfile.header["SQ"]:
if kv["LN"] < 10 * N:
continue
seqsize[kv["SN"]] = kv["LN"] / N + 1
allseqs = natsorted(seqsize.keys())
allseqsizes = np.array([seqsize[x] for x in allseqs])
seqstarts = np.cumsum(allseqsizes)
seqstarts = np.roll(seqstarts, 1)
total_bins = seqstarts[0]
seqstarts[0] = 0
seqstarts = dict(zip(allseqs, seqstarts))
return seqstarts, seqsize, total_bins | python | def get_seqstarts(bamfile, N):
""" Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells
"""
import pysam
bamfile = pysam.AlignmentFile(bamfile, "rb")
seqsize = {}
for kv in bamfile.header["SQ"]:
if kv["LN"] < 10 * N:
continue
seqsize[kv["SN"]] = kv["LN"] / N + 1
allseqs = natsorted(seqsize.keys())
allseqsizes = np.array([seqsize[x] for x in allseqs])
seqstarts = np.cumsum(allseqsizes)
seqstarts = np.roll(seqstarts, 1)
total_bins = seqstarts[0]
seqstarts[0] = 0
seqstarts = dict(zip(allseqs, seqstarts))
return seqstarts, seqsize, total_bins | [
"def",
"get_seqstarts",
"(",
"bamfile",
",",
"N",
")",
":",
"import",
"pysam",
"bamfile",
"=",
"pysam",
".",
"AlignmentFile",
"(",
"bamfile",
",",
"\"rb\"",
")",
"seqsize",
"=",
"{",
"}",
"for",
"kv",
"in",
"bamfile",
".",
"header",
"[",
"\"SQ\"",
"]",... | Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells | [
"Go",
"through",
"the",
"SQ",
"headers",
"and",
"pull",
"out",
"all",
"sequences",
"with",
"size",
"greater",
"than",
"the",
"resolution",
"settings",
"i",
".",
"e",
".",
"contains",
"at",
"least",
"a",
"few",
"cells"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L662-L682 | train | 200,453 |
tanghaibao/jcvi | jcvi/assembly/hic.py | get_distbins | def get_distbins(start=100, bins=2500, ratio=1.01):
""" Get exponentially sized
"""
b = np.ones(bins, dtype="float64")
b[0] = 100
for i in range(1, bins):
b[i] = b[i - 1] * ratio
bins = np.around(b).astype(dtype="int")
binsizes = np.diff(bins)
return bins, binsizes | python | def get_distbins(start=100, bins=2500, ratio=1.01):
""" Get exponentially sized
"""
b = np.ones(bins, dtype="float64")
b[0] = 100
for i in range(1, bins):
b[i] = b[i - 1] * ratio
bins = np.around(b).astype(dtype="int")
binsizes = np.diff(bins)
return bins, binsizes | [
"def",
"get_distbins",
"(",
"start",
"=",
"100",
",",
"bins",
"=",
"2500",
",",
"ratio",
"=",
"1.01",
")",
":",
"b",
"=",
"np",
".",
"ones",
"(",
"bins",
",",
"dtype",
"=",
"\"float64\"",
")",
"b",
"[",
"0",
"]",
"=",
"100",
"for",
"i",
"in",
... | Get exponentially sized | [
"Get",
"exponentially",
"sized"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L685-L694 | train | 200,454 |
tanghaibao/jcvi | jcvi/assembly/hic.py | simulate | def simulate(args):
"""
%prog simulate test
Simulate CLM and IDS files with given names.
The simulator assumes several distributions:
- Links are distributed uniformly across genome
- Log10(link_size) are distributed normally
- Genes are distributed uniformly
"""
p = OptionParser(simulate.__doc__)
p.add_option("--genomesize", default=10000000, type="int",
help="Genome size")
p.add_option("--genes", default=1000, type="int",
help="Number of genes")
p.add_option("--contigs", default=100, type="int",
help="Number of contigs")
p.add_option("--coverage", default=10, type="int",
help="Link coverage")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
pf, = args
GenomeSize = opts.genomesize
Genes = opts.genes
Contigs = opts.contigs
Coverage = opts.coverage
PE = 500
Links = int(GenomeSize * Coverage / PE)
# Simulate the contig sizes that sum to GenomeSize
# See also:
# <https://en.wikipedia.org/wiki/User:Skinnerd/Simplex_Point_Picking>
ContigSizes, = np.random.dirichlet([1] * Contigs, 1) * GenomeSize
ContigSizes = np.array(np.round_(ContigSizes, decimals=0), dtype=int)
ContigStarts = np.zeros(Contigs, dtype=int)
ContigStarts[1:] = np.cumsum(ContigSizes)[:-1]
# Write IDS file
idsfile = pf + ".ids"
fw = open(idsfile, "w")
print("#Contig\tRECounts\tLength", file=fw)
for i, s in enumerate(ContigSizes):
print("tig{:04d}\t{}\t{}".format(i, s / (4 ** 4), s), file=fw)
fw.close()
# Simulate the gene positions
GenePositions = np.sort(np.random.random_integers(0,
GenomeSize - 1, size=Genes))
write_last_and_beds(pf, GenePositions, ContigStarts)
# Simulate links, uniform start, with link distances following 1/x, where x
# is the distance between the links. As an approximation, we have links
# between [1e3, 1e7], so we map from uniform [1e-7, 1e-3]
LinkStarts = np.sort(np.random.random_integers(0, GenomeSize - 1,
size=Links))
a, b = 1e-7, 1e-3
LinkSizes = np.array(np.round_(1 / ((b - a) * np.random.rand(Links) + a),
decimals=0), dtype="int")
LinkEnds = LinkStarts + LinkSizes
# Find link to contig membership
LinkStartContigs = np.searchsorted(ContigStarts, LinkStarts) - 1
LinkEndContigs = np.searchsorted(ContigStarts, LinkEnds) - 1
# Extract inter-contig links
InterContigLinks = (LinkStartContigs != LinkEndContigs) & \
(LinkEndContigs != Contigs)
ICLinkStartContigs = LinkStartContigs[InterContigLinks]
ICLinkEndContigs = LinkEndContigs[InterContigLinks]
ICLinkStarts = LinkStarts[InterContigLinks]
ICLinkEnds = LinkEnds[InterContigLinks]
# Write CLM file
write_clm(pf, ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds,
ContigStarts, ContigSizes) | python | def simulate(args):
"""
%prog simulate test
Simulate CLM and IDS files with given names.
The simulator assumes several distributions:
- Links are distributed uniformly across genome
- Log10(link_size) are distributed normally
- Genes are distributed uniformly
"""
p = OptionParser(simulate.__doc__)
p.add_option("--genomesize", default=10000000, type="int",
help="Genome size")
p.add_option("--genes", default=1000, type="int",
help="Number of genes")
p.add_option("--contigs", default=100, type="int",
help="Number of contigs")
p.add_option("--coverage", default=10, type="int",
help="Link coverage")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
pf, = args
GenomeSize = opts.genomesize
Genes = opts.genes
Contigs = opts.contigs
Coverage = opts.coverage
PE = 500
Links = int(GenomeSize * Coverage / PE)
# Simulate the contig sizes that sum to GenomeSize
# See also:
# <https://en.wikipedia.org/wiki/User:Skinnerd/Simplex_Point_Picking>
ContigSizes, = np.random.dirichlet([1] * Contigs, 1) * GenomeSize
ContigSizes = np.array(np.round_(ContigSizes, decimals=0), dtype=int)
ContigStarts = np.zeros(Contigs, dtype=int)
ContigStarts[1:] = np.cumsum(ContigSizes)[:-1]
# Write IDS file
idsfile = pf + ".ids"
fw = open(idsfile, "w")
print("#Contig\tRECounts\tLength", file=fw)
for i, s in enumerate(ContigSizes):
print("tig{:04d}\t{}\t{}".format(i, s / (4 ** 4), s), file=fw)
fw.close()
# Simulate the gene positions
GenePositions = np.sort(np.random.random_integers(0,
GenomeSize - 1, size=Genes))
write_last_and_beds(pf, GenePositions, ContigStarts)
# Simulate links, uniform start, with link distances following 1/x, where x
# is the distance between the links. As an approximation, we have links
# between [1e3, 1e7], so we map from uniform [1e-7, 1e-3]
LinkStarts = np.sort(np.random.random_integers(0, GenomeSize - 1,
size=Links))
a, b = 1e-7, 1e-3
LinkSizes = np.array(np.round_(1 / ((b - a) * np.random.rand(Links) + a),
decimals=0), dtype="int")
LinkEnds = LinkStarts + LinkSizes
# Find link to contig membership
LinkStartContigs = np.searchsorted(ContigStarts, LinkStarts) - 1
LinkEndContigs = np.searchsorted(ContigStarts, LinkEnds) - 1
# Extract inter-contig links
InterContigLinks = (LinkStartContigs != LinkEndContigs) & \
(LinkEndContigs != Contigs)
ICLinkStartContigs = LinkStartContigs[InterContigLinks]
ICLinkEndContigs = LinkEndContigs[InterContigLinks]
ICLinkStarts = LinkStarts[InterContigLinks]
ICLinkEnds = LinkEnds[InterContigLinks]
# Write CLM file
write_clm(pf, ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds,
ContigStarts, ContigSizes) | [
"def",
"simulate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"simulate",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--genomesize\"",
",",
"default",
"=",
"10000000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Genome size\"",
... | %prog simulate test
Simulate CLM and IDS files with given names.
The simulator assumes several distributions:
- Links are distributed uniformly across genome
- Log10(link_size) are distributed normally
- Genes are distributed uniformly | [
"%prog",
"simulate",
"test"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L799-L878 | train | 200,455 |
tanghaibao/jcvi | jcvi/assembly/hic.py | write_last_and_beds | def write_last_and_beds(pf, GenePositions, ContigStarts):
"""
Write LAST file, query and subject BED files.
"""
qbedfile = pf + "tigs.bed"
sbedfile = pf + "chr.bed"
lastfile = "{}tigs.{}chr.last".format(pf, pf)
qbedfw = open(qbedfile, "w")
sbedfw = open(sbedfile, "w")
lastfw = open(lastfile, "w")
GeneContigs = np.searchsorted(ContigStarts, GenePositions) - 1
for i, (c, gstart) in enumerate(zip(GeneContigs, GenePositions)):
gene = "gene{:05d}".format(i)
tig = "tig{:04d}".format(c)
start = ContigStarts[c]
cstart = gstart - start
print("\t".join(str(x) for x in
(tig, cstart, cstart + 1, gene)), file=qbedfw)
print("\t".join(str(x) for x in
("chr1", gstart, gstart + 1, gene)), file=sbedfw)
lastatoms = [gene, gene, 100] + [0] * 8 + [100]
print("\t".join(str(x) for x in lastatoms), file=lastfw)
qbedfw.close()
sbedfw.close()
lastfw.close() | python | def write_last_and_beds(pf, GenePositions, ContigStarts):
"""
Write LAST file, query and subject BED files.
"""
qbedfile = pf + "tigs.bed"
sbedfile = pf + "chr.bed"
lastfile = "{}tigs.{}chr.last".format(pf, pf)
qbedfw = open(qbedfile, "w")
sbedfw = open(sbedfile, "w")
lastfw = open(lastfile, "w")
GeneContigs = np.searchsorted(ContigStarts, GenePositions) - 1
for i, (c, gstart) in enumerate(zip(GeneContigs, GenePositions)):
gene = "gene{:05d}".format(i)
tig = "tig{:04d}".format(c)
start = ContigStarts[c]
cstart = gstart - start
print("\t".join(str(x) for x in
(tig, cstart, cstart + 1, gene)), file=qbedfw)
print("\t".join(str(x) for x in
("chr1", gstart, gstart + 1, gene)), file=sbedfw)
lastatoms = [gene, gene, 100] + [0] * 8 + [100]
print("\t".join(str(x) for x in lastatoms), file=lastfw)
qbedfw.close()
sbedfw.close()
lastfw.close() | [
"def",
"write_last_and_beds",
"(",
"pf",
",",
"GenePositions",
",",
"ContigStarts",
")",
":",
"qbedfile",
"=",
"pf",
"+",
"\"tigs.bed\"",
"sbedfile",
"=",
"pf",
"+",
"\"chr.bed\"",
"lastfile",
"=",
"\"{}tigs.{}chr.last\"",
".",
"format",
"(",
"pf",
",",
"pf",
... | Write LAST file, query and subject BED files. | [
"Write",
"LAST",
"file",
"query",
"and",
"subject",
"BED",
"files",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L881-L907 | train | 200,456 |
tanghaibao/jcvi | jcvi/assembly/hic.py | write_clm | def write_clm(pf, ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds,
ContigStarts, ContigSizes):
"""
Write CLM file from simulated data.
"""
clm = defaultdict(list)
for start, end, linkstart, linkend in \
zip(ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds):
start_a = ContigStarts[start]
start_b = start_a + ContigSizes[start]
end_a = ContigStarts[end]
end_b = end_a + ContigSizes[end]
if linkend >= end_b:
continue
clm[(start, end)].append((linkstart - start_a, start_b - linkstart,
linkend - end_a, end_b - linkend))
clmfile = pf + ".clm"
fw = open(clmfile, "w")
def format_array(a):
return [str(x) for x in sorted(a) if x > 0]
for (start, end), links in sorted(clm.items()):
start = "tig{:04d}".format(start)
end = "tig{:04d}".format(end)
nlinks = len(links)
if not nlinks:
continue
ff = format_array([(b + c) for a, b, c, d in links])
fr = format_array([(b + d) for a, b, c, d in links])
rf = format_array([(a + c) for a, b, c, d in links])
rr = format_array([(a + d) for a, b, c, d in links])
print("{}+ {}+\t{}\t{}".format(start, end, nlinks, " ".join(ff)), file=fw)
print("{}+ {}-\t{}\t{}".format(start, end, nlinks, " ".join(fr)), file=fw)
print("{}- {}+\t{}\t{}".format(start, end, nlinks, " ".join(rf)), file=fw)
print("{}- {}-\t{}\t{}".format(start, end, nlinks, " ".join(rr)), file=fw)
fw.close() | python | def write_clm(pf, ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds,
ContigStarts, ContigSizes):
"""
Write CLM file from simulated data.
"""
clm = defaultdict(list)
for start, end, linkstart, linkend in \
zip(ICLinkStartContigs, ICLinkEndContigs,
ICLinkStarts, ICLinkEnds):
start_a = ContigStarts[start]
start_b = start_a + ContigSizes[start]
end_a = ContigStarts[end]
end_b = end_a + ContigSizes[end]
if linkend >= end_b:
continue
clm[(start, end)].append((linkstart - start_a, start_b - linkstart,
linkend - end_a, end_b - linkend))
clmfile = pf + ".clm"
fw = open(clmfile, "w")
def format_array(a):
return [str(x) for x in sorted(a) if x > 0]
for (start, end), links in sorted(clm.items()):
start = "tig{:04d}".format(start)
end = "tig{:04d}".format(end)
nlinks = len(links)
if not nlinks:
continue
ff = format_array([(b + c) for a, b, c, d in links])
fr = format_array([(b + d) for a, b, c, d in links])
rf = format_array([(a + c) for a, b, c, d in links])
rr = format_array([(a + d) for a, b, c, d in links])
print("{}+ {}+\t{}\t{}".format(start, end, nlinks, " ".join(ff)), file=fw)
print("{}+ {}-\t{}\t{}".format(start, end, nlinks, " ".join(fr)), file=fw)
print("{}- {}+\t{}\t{}".format(start, end, nlinks, " ".join(rf)), file=fw)
print("{}- {}-\t{}\t{}".format(start, end, nlinks, " ".join(rr)), file=fw)
fw.close() | [
"def",
"write_clm",
"(",
"pf",
",",
"ICLinkStartContigs",
",",
"ICLinkEndContigs",
",",
"ICLinkStarts",
",",
"ICLinkEnds",
",",
"ContigStarts",
",",
"ContigSizes",
")",
":",
"clm",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"start",
",",
"end",
",",
"links... | Write CLM file from simulated data. | [
"Write",
"CLM",
"file",
"from",
"simulated",
"data",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L910-L949 | train | 200,457 |
tanghaibao/jcvi | jcvi/assembly/hic.py | density | def density(args):
"""
%prog density test.clm
Estimate link density of contigs.
"""
p = OptionParser(density.__doc__)
p.add_option("--save", default=False, action="store_true",
help="Write log densitites of contigs to file")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clmfile, = args
clm = CLMFile(clmfile)
pf = clmfile.rsplit(".", 1)[0]
if opts.save:
logdensities = clm.calculate_densities()
densityfile = pf + ".density"
fw = open(densityfile, "w")
for name, logd in logdensities.items():
s = clm.tig_to_size[name]
print("\t".join(str(x) for x in (name, s, logd)), file=fw)
fw.close()
logging.debug("Density written to `{}`".format(densityfile))
tourfile = clmfile.rsplit(".", 1)[0] + ".tour"
tour = clm.activate(tourfile=tourfile, backuptour=False)
clm.flip_all(tour)
clm.flip_whole(tour)
clm.flip_one(tour) | python | def density(args):
"""
%prog density test.clm
Estimate link density of contigs.
"""
p = OptionParser(density.__doc__)
p.add_option("--save", default=False, action="store_true",
help="Write log densitites of contigs to file")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clmfile, = args
clm = CLMFile(clmfile)
pf = clmfile.rsplit(".", 1)[0]
if opts.save:
logdensities = clm.calculate_densities()
densityfile = pf + ".density"
fw = open(densityfile, "w")
for name, logd in logdensities.items():
s = clm.tig_to_size[name]
print("\t".join(str(x) for x in (name, s, logd)), file=fw)
fw.close()
logging.debug("Density written to `{}`".format(densityfile))
tourfile = clmfile.rsplit(".", 1)[0] + ".tour"
tour = clm.activate(tourfile=tourfile, backuptour=False)
clm.flip_all(tour)
clm.flip_whole(tour)
clm.flip_one(tour) | [
"def",
"density",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"density",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--save\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Write log densitites... | %prog density test.clm
Estimate link density of contigs. | [
"%prog",
"density",
"test",
".",
"clm"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L952-L985 | train | 200,458 |
tanghaibao/jcvi | jcvi/assembly/hic.py | optimize | def optimize(args):
"""
%prog optimize test.clm
Optimize the contig order and orientation, based on CLM file.
"""
p = OptionParser(optimize.__doc__)
p.add_option("--skiprecover", default=False, action="store_true",
help="Do not import 'recover' contigs")
p.add_option("--startover", default=False, action="store_true",
help="Do not resume from existing tour file")
p.add_option("--skipGA", default=False, action="store_true",
help="Skip GA step")
p.set_outfile(outfile=None)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clmfile, = args
startover = opts.startover
runGA = not opts.skipGA
cpus = opts.cpus
# Load contact map
clm = CLMFile(clmfile, skiprecover=opts.skiprecover)
tourfile = opts.outfile or clmfile.rsplit(".", 1)[0] + ".tour"
if startover:
tourfile = None
tour = clm.activate(tourfile=tourfile)
fwtour = open(tourfile, "w")
# Store INIT tour
print_tour(fwtour, clm.tour, "INIT",
clm.active_contigs, clm.oo, signs=clm.signs)
if runGA:
for phase in range(1, 3):
tour = optimize_ordering(fwtour, clm, phase, cpus)
tour = clm.prune_tour(tour, cpus)
# Flip orientations
phase = 1
while True:
tag1, tag2 = optimize_orientations(fwtour, clm, phase, cpus)
if tag1 == REJECT and tag2 == REJECT:
logging.debug("Terminating ... no more {}".format(ACCEPT))
break
phase += 1
fwtour.close() | python | def optimize(args):
"""
%prog optimize test.clm
Optimize the contig order and orientation, based on CLM file.
"""
p = OptionParser(optimize.__doc__)
p.add_option("--skiprecover", default=False, action="store_true",
help="Do not import 'recover' contigs")
p.add_option("--startover", default=False, action="store_true",
help="Do not resume from existing tour file")
p.add_option("--skipGA", default=False, action="store_true",
help="Skip GA step")
p.set_outfile(outfile=None)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clmfile, = args
startover = opts.startover
runGA = not opts.skipGA
cpus = opts.cpus
# Load contact map
clm = CLMFile(clmfile, skiprecover=opts.skiprecover)
tourfile = opts.outfile or clmfile.rsplit(".", 1)[0] + ".tour"
if startover:
tourfile = None
tour = clm.activate(tourfile=tourfile)
fwtour = open(tourfile, "w")
# Store INIT tour
print_tour(fwtour, clm.tour, "INIT",
clm.active_contigs, clm.oo, signs=clm.signs)
if runGA:
for phase in range(1, 3):
tour = optimize_ordering(fwtour, clm, phase, cpus)
tour = clm.prune_tour(tour, cpus)
# Flip orientations
phase = 1
while True:
tag1, tag2 = optimize_orientations(fwtour, clm, phase, cpus)
if tag1 == REJECT and tag2 == REJECT:
logging.debug("Terminating ... no more {}".format(ACCEPT))
break
phase += 1
fwtour.close() | [
"def",
"optimize",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"optimize",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--skiprecover\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Do not impo... | %prog optimize test.clm
Optimize the contig order and orientation, based on CLM file. | [
"%prog",
"optimize",
"test",
".",
"clm"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L988-L1040 | train | 200,459 |
tanghaibao/jcvi | jcvi/assembly/hic.py | optimize_orientations | def optimize_orientations(fwtour, clm, phase, cpus):
"""
Optimize the orientations of contigs by using heuristic flipping.
"""
# Prepare input files
tour_contigs = clm.active_contigs
tour = clm.tour
oo = clm.oo
print_tour(fwtour, tour, "FLIPALL{}".format(phase),
tour_contigs, oo, signs=clm.signs)
tag1 = clm.flip_whole(tour)
print_tour(fwtour, tour, "FLIPWHOLE{}".format(phase),
tour_contigs, oo, signs=clm.signs)
tag2 = clm.flip_one(tour)
print_tour(fwtour, tour, "FLIPONE{}".format(phase),
tour_contigs, oo, signs=clm.signs)
return tag1, tag2 | python | def optimize_orientations(fwtour, clm, phase, cpus):
"""
Optimize the orientations of contigs by using heuristic flipping.
"""
# Prepare input files
tour_contigs = clm.active_contigs
tour = clm.tour
oo = clm.oo
print_tour(fwtour, tour, "FLIPALL{}".format(phase),
tour_contigs, oo, signs=clm.signs)
tag1 = clm.flip_whole(tour)
print_tour(fwtour, tour, "FLIPWHOLE{}".format(phase),
tour_contigs, oo, signs=clm.signs)
tag2 = clm.flip_one(tour)
print_tour(fwtour, tour, "FLIPONE{}".format(phase),
tour_contigs, oo, signs=clm.signs)
return tag1, tag2 | [
"def",
"optimize_orientations",
"(",
"fwtour",
",",
"clm",
",",
"phase",
",",
"cpus",
")",
":",
"# Prepare input files",
"tour_contigs",
"=",
"clm",
".",
"active_contigs",
"tour",
"=",
"clm",
".",
"tour",
"oo",
"=",
"clm",
".",
"oo",
"print_tour",
"(",
"fw... | Optimize the orientations of contigs by using heuristic flipping. | [
"Optimize",
"the",
"orientations",
"of",
"contigs",
"by",
"using",
"heuristic",
"flipping",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1078-L1096 | train | 200,460 |
tanghaibao/jcvi | jcvi/assembly/hic.py | iter_last_tour | def iter_last_tour(tourfile, clm):
"""
Extract last tour from tourfile. The clm instance is also passed in to see
if any contig is covered in the clm.
"""
row = open(tourfile).readlines()[-1]
_tour, _tour_o = separate_tour_and_o(row)
tour = []
tour_o = []
for tc, to in zip(_tour, _tour_o):
if tc not in clm.contigs:
logging.debug("Contig `{}` in file `{}` not found in `{}`"
.format(tc, tourfile, clm.idsfile))
continue
tour.append(tc)
tour_o.append(to)
return tour, tour_o | python | def iter_last_tour(tourfile, clm):
"""
Extract last tour from tourfile. The clm instance is also passed in to see
if any contig is covered in the clm.
"""
row = open(tourfile).readlines()[-1]
_tour, _tour_o = separate_tour_and_o(row)
tour = []
tour_o = []
for tc, to in zip(_tour, _tour_o):
if tc not in clm.contigs:
logging.debug("Contig `{}` in file `{}` not found in `{}`"
.format(tc, tourfile, clm.idsfile))
continue
tour.append(tc)
tour_o.append(to)
return tour, tour_o | [
"def",
"iter_last_tour",
"(",
"tourfile",
",",
"clm",
")",
":",
"row",
"=",
"open",
"(",
"tourfile",
")",
".",
"readlines",
"(",
")",
"[",
"-",
"1",
"]",
"_tour",
",",
"_tour_o",
"=",
"separate_tour_and_o",
"(",
"row",
")",
"tour",
"=",
"[",
"]",
"... | Extract last tour from tourfile. The clm instance is also passed in to see
if any contig is covered in the clm. | [
"Extract",
"last",
"tour",
"from",
"tourfile",
".",
"The",
"clm",
"instance",
"is",
"also",
"passed",
"in",
"to",
"see",
"if",
"any",
"contig",
"is",
"covered",
"in",
"the",
"clm",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1149-L1165 | train | 200,461 |
tanghaibao/jcvi | jcvi/assembly/hic.py | iter_tours | def iter_tours(tourfile, frames=1):
"""
Extract tours from tourfile. Tourfile contains a set of contig
configurations, generated at each iteration of the genetic algorithm. Each
configuration has two rows, first row contains iteration id and score,
second row contains list of contigs, separated by comma.
"""
fp = open(tourfile)
i = 0
for row in fp:
if row[0] == '>':
label = row[1:].strip()
if label.startswith("GA"):
pf, j, score = label.split("-", 2)
j = int(j)
else:
j = 0
i += 1
else:
if j % frames != 0:
continue
tour, tour_o = separate_tour_and_o(row)
yield i, label, tour, tour_o
fp.close() | python | def iter_tours(tourfile, frames=1):
"""
Extract tours from tourfile. Tourfile contains a set of contig
configurations, generated at each iteration of the genetic algorithm. Each
configuration has two rows, first row contains iteration id and score,
second row contains list of contigs, separated by comma.
"""
fp = open(tourfile)
i = 0
for row in fp:
if row[0] == '>':
label = row[1:].strip()
if label.startswith("GA"):
pf, j, score = label.split("-", 2)
j = int(j)
else:
j = 0
i += 1
else:
if j % frames != 0:
continue
tour, tour_o = separate_tour_and_o(row)
yield i, label, tour, tour_o
fp.close() | [
"def",
"iter_tours",
"(",
"tourfile",
",",
"frames",
"=",
"1",
")",
":",
"fp",
"=",
"open",
"(",
"tourfile",
")",
"i",
"=",
"0",
"for",
"row",
"in",
"fp",
":",
"if",
"row",
"[",
"0",
"]",
"==",
"'>'",
":",
"label",
"=",
"row",
"[",
"1",
":",
... | Extract tours from tourfile. Tourfile contains a set of contig
configurations, generated at each iteration of the genetic algorithm. Each
configuration has two rows, first row contains iteration id and score,
second row contains list of contigs, separated by comma. | [
"Extract",
"tours",
"from",
"tourfile",
".",
"Tourfile",
"contains",
"a",
"set",
"of",
"contig",
"configurations",
"generated",
"at",
"each",
"iteration",
"of",
"the",
"genetic",
"algorithm",
".",
"Each",
"configuration",
"has",
"two",
"rows",
"first",
"row",
... | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1168-L1193 | train | 200,462 |
tanghaibao/jcvi | jcvi/assembly/hic.py | movie | def movie(args):
"""
%prog movie test.tour test.clm ref.contigs.last
Plot optimization history.
"""
p = OptionParser(movie.__doc__)
p.add_option("--frames", default=500, type="int",
help="Only plot every N frames")
p.add_option("--engine", default="ffmpeg", choices=("ffmpeg", "gifsicle"),
help="Movie engine, output MP4 or GIF")
p.set_beds()
opts, args, iopts = p.set_image_options(args, figsize="16x8",
style="white", cmap="coolwarm",
format="png", dpi=300)
if len(args) != 3:
sys.exit(not p.print_help())
tourfile, clmfile, lastfile = args
tourfile = op.abspath(tourfile)
clmfile = op.abspath(clmfile)
lastfile = op.abspath(lastfile)
cwd = os.getcwd()
odir = op.basename(tourfile).rsplit(".", 1)[0] + "-movie"
anchorsfile, qbedfile, contig_to_beds = \
prepare_synteny(tourfile, lastfile, odir, p, opts)
args = []
for i, label, tour, tour_o in iter_tours(tourfile, frames=opts.frames):
padi = "{:06d}".format(i)
# Make sure the anchorsfile and bedfile has the serial number in,
# otherwise parallelization may fail
a, b = op.basename(anchorsfile).split(".", 1)
ianchorsfile = a + "_" + padi + "." + b
symlink(anchorsfile, ianchorsfile)
# Make BED file with new order
qb = Bed()
for contig, o in zip(tour, tour_o):
if contig not in contig_to_beds:
continue
bedlines = contig_to_beds[contig][:]
if o == '-':
bedlines.reverse()
for x in bedlines:
qb.append(x)
a, b = op.basename(qbedfile).split(".", 1)
ibedfile = a + "_" + padi + "." + b
qb.print_to_file(ibedfile)
# Plot dot plot, but do not sort contigs by name (otherwise losing
# order)
image_name = padi + "." + iopts.format
tour = ",".join(tour)
args.append([[tour, clmfile, ianchorsfile,
"--outfile", image_name, "--label", label]])
Jobs(movieframe, args).run()
os.chdir(cwd)
make_movie(odir, odir, engine=opts.engine, format=iopts.format) | python | def movie(args):
"""
%prog movie test.tour test.clm ref.contigs.last
Plot optimization history.
"""
p = OptionParser(movie.__doc__)
p.add_option("--frames", default=500, type="int",
help="Only plot every N frames")
p.add_option("--engine", default="ffmpeg", choices=("ffmpeg", "gifsicle"),
help="Movie engine, output MP4 or GIF")
p.set_beds()
opts, args, iopts = p.set_image_options(args, figsize="16x8",
style="white", cmap="coolwarm",
format="png", dpi=300)
if len(args) != 3:
sys.exit(not p.print_help())
tourfile, clmfile, lastfile = args
tourfile = op.abspath(tourfile)
clmfile = op.abspath(clmfile)
lastfile = op.abspath(lastfile)
cwd = os.getcwd()
odir = op.basename(tourfile).rsplit(".", 1)[0] + "-movie"
anchorsfile, qbedfile, contig_to_beds = \
prepare_synteny(tourfile, lastfile, odir, p, opts)
args = []
for i, label, tour, tour_o in iter_tours(tourfile, frames=opts.frames):
padi = "{:06d}".format(i)
# Make sure the anchorsfile and bedfile has the serial number in,
# otherwise parallelization may fail
a, b = op.basename(anchorsfile).split(".", 1)
ianchorsfile = a + "_" + padi + "." + b
symlink(anchorsfile, ianchorsfile)
# Make BED file with new order
qb = Bed()
for contig, o in zip(tour, tour_o):
if contig not in contig_to_beds:
continue
bedlines = contig_to_beds[contig][:]
if o == '-':
bedlines.reverse()
for x in bedlines:
qb.append(x)
a, b = op.basename(qbedfile).split(".", 1)
ibedfile = a + "_" + padi + "." + b
qb.print_to_file(ibedfile)
# Plot dot plot, but do not sort contigs by name (otherwise losing
# order)
image_name = padi + "." + iopts.format
tour = ",".join(tour)
args.append([[tour, clmfile, ianchorsfile,
"--outfile", image_name, "--label", label]])
Jobs(movieframe, args).run()
os.chdir(cwd)
make_movie(odir, odir, engine=opts.engine, format=iopts.format) | [
"def",
"movie",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"movie",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--frames\"",
",",
"default",
"=",
"500",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Only plot every N frames\"",
")... | %prog movie test.tour test.clm ref.contigs.last
Plot optimization history. | [
"%prog",
"movie",
"test",
".",
"tour",
"test",
".",
"clm",
"ref",
".",
"contigs",
".",
"last"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1196-L1258 | train | 200,463 |
tanghaibao/jcvi | jcvi/assembly/hic.py | prepare_ec | def prepare_ec(oo, sizes, M):
"""
This prepares EC and converts from contig_id to an index.
"""
tour = range(len(oo))
tour_sizes = np.array([sizes.sizes[x] for x in oo])
tour_M = M[oo, :][:, oo]
return tour, tour_sizes, tour_M | python | def prepare_ec(oo, sizes, M):
"""
This prepares EC and converts from contig_id to an index.
"""
tour = range(len(oo))
tour_sizes = np.array([sizes.sizes[x] for x in oo])
tour_M = M[oo, :][:, oo]
return tour, tour_sizes, tour_M | [
"def",
"prepare_ec",
"(",
"oo",
",",
"sizes",
",",
"M",
")",
":",
"tour",
"=",
"range",
"(",
"len",
"(",
"oo",
")",
")",
"tour_sizes",
"=",
"np",
".",
"array",
"(",
"[",
"sizes",
".",
"sizes",
"[",
"x",
"]",
"for",
"x",
"in",
"oo",
"]",
")",
... | This prepares EC and converts from contig_id to an index. | [
"This",
"prepares",
"EC",
"and",
"converts",
"from",
"contig_id",
"to",
"an",
"index",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1345-L1352 | train | 200,464 |
tanghaibao/jcvi | jcvi/assembly/hic.py | score_evaluate | def score_evaluate(tour, tour_sizes=None, tour_M=None):
""" SLOW python version of the evaluation function. For benchmarking
purposes only. Do not use in production.
"""
sizes_oo = np.array([tour_sizes[x] for x in tour])
sizes_cum = np.cumsum(sizes_oo) - sizes_oo / 2
s = 0
size = len(tour)
for ia in xrange(size):
a = tour[ia]
for ib in xrange(ia + 1, size):
b = tour[ib]
links = tour_M[a, b]
dist = sizes_cum[ib] - sizes_cum[ia]
if dist > 1e7:
break
s += links * 1. / dist
return s, | python | def score_evaluate(tour, tour_sizes=None, tour_M=None):
""" SLOW python version of the evaluation function. For benchmarking
purposes only. Do not use in production.
"""
sizes_oo = np.array([tour_sizes[x] for x in tour])
sizes_cum = np.cumsum(sizes_oo) - sizes_oo / 2
s = 0
size = len(tour)
for ia in xrange(size):
a = tour[ia]
for ib in xrange(ia + 1, size):
b = tour[ib]
links = tour_M[a, b]
dist = sizes_cum[ib] - sizes_cum[ia]
if dist > 1e7:
break
s += links * 1. / dist
return s, | [
"def",
"score_evaluate",
"(",
"tour",
",",
"tour_sizes",
"=",
"None",
",",
"tour_M",
"=",
"None",
")",
":",
"sizes_oo",
"=",
"np",
".",
"array",
"(",
"[",
"tour_sizes",
"[",
"x",
"]",
"for",
"x",
"in",
"tour",
"]",
")",
"sizes_cum",
"=",
"np",
".",... | SLOW python version of the evaluation function. For benchmarking
purposes only. Do not use in production. | [
"SLOW",
"python",
"version",
"of",
"the",
"evaluation",
"function",
".",
"For",
"benchmarking",
"purposes",
"only",
".",
"Do",
"not",
"use",
"in",
"production",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1355-L1372 | train | 200,465 |
tanghaibao/jcvi | jcvi/assembly/hic.py | movieframe | def movieframe(args):
"""
%prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot.
"""
p = OptionParser(movieframe.__doc__)
p.add_option("--label", help="Figure title")
p.set_beds()
p.set_outfile(outfile=None)
opts, args, iopts = p.set_image_options(args, figsize="16x8",
style="white", cmap="coolwarm",
format="png", dpi=120)
if len(args) != 3:
sys.exit(not p.print_help())
tour, clmfile, anchorsfile = args
tour = tour.split(",")
image_name = opts.outfile or ("movieframe." + iopts.format)
label = opts.label or op.basename(image_name).rsplit(".", 1)[0]
clm = CLMFile(clmfile)
totalbins, bins, breaks = make_bins(tour, clm.tig_to_size)
M = read_clm(clm, totalbins, bins)
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1]) # whole canvas
ax1 = fig.add_axes([.05, .1, .4, .8]) # heatmap
ax2 = fig.add_axes([.55, .1, .4, .8]) # dot plot
ax2_root = fig.add_axes([.5, 0, .5, 1]) # dot plot canvas
# Left axis: heatmap
plot_heatmap(ax1, M, breaks, iopts)
# Right axis: synteny
qbed, sbed, qorder, sorder, is_self = check_beds(anchorsfile, p, opts,
sorted=False)
dotplot(anchorsfile, qbed, sbed, fig, ax2_root, ax2, sep=False, title="")
root.text(.5, .98, clm.name, color="g", ha="center", va="center")
root.text(.5, .95, label, color="darkslategray", ha="center", va="center")
normalize_axes(root)
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | python | def movieframe(args):
"""
%prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot.
"""
p = OptionParser(movieframe.__doc__)
p.add_option("--label", help="Figure title")
p.set_beds()
p.set_outfile(outfile=None)
opts, args, iopts = p.set_image_options(args, figsize="16x8",
style="white", cmap="coolwarm",
format="png", dpi=120)
if len(args) != 3:
sys.exit(not p.print_help())
tour, clmfile, anchorsfile = args
tour = tour.split(",")
image_name = opts.outfile or ("movieframe." + iopts.format)
label = opts.label or op.basename(image_name).rsplit(".", 1)[0]
clm = CLMFile(clmfile)
totalbins, bins, breaks = make_bins(tour, clm.tig_to_size)
M = read_clm(clm, totalbins, bins)
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1]) # whole canvas
ax1 = fig.add_axes([.05, .1, .4, .8]) # heatmap
ax2 = fig.add_axes([.55, .1, .4, .8]) # dot plot
ax2_root = fig.add_axes([.5, 0, .5, 1]) # dot plot canvas
# Left axis: heatmap
plot_heatmap(ax1, M, breaks, iopts)
# Right axis: synteny
qbed, sbed, qorder, sorder, is_self = check_beds(anchorsfile, p, opts,
sorted=False)
dotplot(anchorsfile, qbed, sbed, fig, ax2_root, ax2, sep=False, title="")
root.text(.5, .98, clm.name, color="g", ha="center", va="center")
root.text(.5, .95, label, color="darkslategray", ha="center", va="center")
normalize_axes(root)
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | [
"def",
"movieframe",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"movieframe",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--label\"",
",",
"help",
"=",
"\"Figure title\"",
")",
"p",
".",
"set_beds",
"(",
")",
"p",
".",
"set_outfile",
... | %prog movieframe tour test.clm contigs.ref.anchors
Draw heatmap and synteny in the same plot. | [
"%prog",
"movieframe",
"tour",
"test",
".",
"clm",
"contigs",
".",
"ref",
".",
"anchors"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1375-L1418 | train | 200,466 |
tanghaibao/jcvi | jcvi/assembly/hic.py | ContigOrdering.write_agp | def write_agp(self, obj, sizes, fw=sys.stdout, gapsize=100,
gaptype="contig", evidence="map"):
'''Converts the ContigOrdering file into AGP format
'''
contigorder = [(x.contig_name, x.strand) for x in self]
order_to_agp(obj, contigorder, sizes, fw,
gapsize=gapsize, gaptype=gaptype, evidence=evidence) | python | def write_agp(self, obj, sizes, fw=sys.stdout, gapsize=100,
gaptype="contig", evidence="map"):
'''Converts the ContigOrdering file into AGP format
'''
contigorder = [(x.contig_name, x.strand) for x in self]
order_to_agp(obj, contigorder, sizes, fw,
gapsize=gapsize, gaptype=gaptype, evidence=evidence) | [
"def",
"write_agp",
"(",
"self",
",",
"obj",
",",
"sizes",
",",
"fw",
"=",
"sys",
".",
"stdout",
",",
"gapsize",
"=",
"100",
",",
"gaptype",
"=",
"\"contig\"",
",",
"evidence",
"=",
"\"map\"",
")",
":",
"contigorder",
"=",
"[",
"(",
"x",
".",
"cont... | Converts the ContigOrdering file into AGP format | [
"Converts",
"the",
"ContigOrdering",
"file",
"into",
"AGP",
"format"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L80-L86 | train | 200,467 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.parse_ids | def parse_ids(self, skiprecover):
'''IDS file has a list of contigs that need to be ordered. 'recover',
keyword, if available in the third column, is less confident.
tig00015093 46912
tig00035238 46779 recover
tig00030900 119291
'''
idsfile = self.idsfile
logging.debug("Parse idsfile `{}`".format(idsfile))
fp = open(idsfile)
tigs = []
for row in fp:
if row[0] == '#': # Header
continue
atoms = row.split()
tig, size = atoms[:2]
size = int(size)
if skiprecover and len(atoms) == 3 and atoms[2] == 'recover':
continue
tigs.append((tig, size))
# Arrange contig names and sizes
_tigs, _sizes = zip(*tigs)
self.contigs = set(_tigs)
self.sizes = np.array(_sizes)
self.tig_to_size = dict(tigs)
# Initially all contigs are considered active
self.active = set(_tigs) | python | def parse_ids(self, skiprecover):
'''IDS file has a list of contigs that need to be ordered. 'recover',
keyword, if available in the third column, is less confident.
tig00015093 46912
tig00035238 46779 recover
tig00030900 119291
'''
idsfile = self.idsfile
logging.debug("Parse idsfile `{}`".format(idsfile))
fp = open(idsfile)
tigs = []
for row in fp:
if row[0] == '#': # Header
continue
atoms = row.split()
tig, size = atoms[:2]
size = int(size)
if skiprecover and len(atoms) == 3 and atoms[2] == 'recover':
continue
tigs.append((tig, size))
# Arrange contig names and sizes
_tigs, _sizes = zip(*tigs)
self.contigs = set(_tigs)
self.sizes = np.array(_sizes)
self.tig_to_size = dict(tigs)
# Initially all contigs are considered active
self.active = set(_tigs) | [
"def",
"parse_ids",
"(",
"self",
",",
"skiprecover",
")",
":",
"idsfile",
"=",
"self",
".",
"idsfile",
"logging",
".",
"debug",
"(",
"\"Parse idsfile `{}`\"",
".",
"format",
"(",
"idsfile",
")",
")",
"fp",
"=",
"open",
"(",
"idsfile",
")",
"tigs",
"=",
... | IDS file has a list of contigs that need to be ordered. 'recover',
keyword, if available in the third column, is less confident.
tig00015093 46912
tig00035238 46779 recover
tig00030900 119291 | [
"IDS",
"file",
"has",
"a",
"list",
"of",
"contigs",
"that",
"need",
"to",
"be",
"ordered",
".",
"recover",
"keyword",
"if",
"available",
"in",
"the",
"third",
"column",
"is",
"less",
"confident",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L109-L138 | train | 200,468 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.calculate_densities | def calculate_densities(self):
"""
Calculate the density of inter-contig links per base. Strong contigs
considered to have high level of inter-contig links in the current
partition.
"""
active = self.active
densities = defaultdict(int)
for (at, bt), links in self.contacts.items():
if not (at in active and bt in active):
continue
densities[at] += links
densities[bt] += links
logdensities = {}
for x, d in densities.items():
s = self.tig_to_size[x]
logd = np.log10(d * 1. / min(s, 500000))
logdensities[x] = logd
return logdensities | python | def calculate_densities(self):
"""
Calculate the density of inter-contig links per base. Strong contigs
considered to have high level of inter-contig links in the current
partition.
"""
active = self.active
densities = defaultdict(int)
for (at, bt), links in self.contacts.items():
if not (at in active and bt in active):
continue
densities[at] += links
densities[bt] += links
logdensities = {}
for x, d in densities.items():
s = self.tig_to_size[x]
logd = np.log10(d * 1. / min(s, 500000))
logdensities[x] = logd
return logdensities | [
"def",
"calculate_densities",
"(",
"self",
")",
":",
"active",
"=",
"self",
".",
"active",
"densities",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"(",
"at",
",",
"bt",
")",
",",
"links",
"in",
"self",
".",
"contacts",
".",
"items",
"(",
")",
":",
... | Calculate the density of inter-contig links per base. Strong contigs
considered to have high level of inter-contig links in the current
partition. | [
"Calculate",
"the",
"density",
"of",
"inter",
"-",
"contig",
"links",
"per",
"base",
".",
"Strong",
"contigs",
"considered",
"to",
"have",
"high",
"level",
"of",
"inter",
"-",
"contig",
"links",
"in",
"the",
"current",
"partition",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L175-L195 | train | 200,469 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.evaluate_tour_M | def evaluate_tour_M(self, tour):
""" Use Cythonized version to evaluate the score of a current tour
"""
from .chic import score_evaluate_M
return score_evaluate_M(tour, self.active_sizes, self.M) | python | def evaluate_tour_M(self, tour):
""" Use Cythonized version to evaluate the score of a current tour
"""
from .chic import score_evaluate_M
return score_evaluate_M(tour, self.active_sizes, self.M) | [
"def",
"evaluate_tour_M",
"(",
"self",
",",
"tour",
")",
":",
"from",
".",
"chic",
"import",
"score_evaluate_M",
"return",
"score_evaluate_M",
"(",
"tour",
",",
"self",
".",
"active_sizes",
",",
"self",
".",
"M",
")"
] | Use Cythonized version to evaluate the score of a current tour | [
"Use",
"Cythonized",
"version",
"to",
"evaluate",
"the",
"score",
"of",
"a",
"current",
"tour"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L262-L266 | train | 200,470 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.evaluate_tour_P | def evaluate_tour_P(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
with better precision on the distance of the contigs.
"""
from .chic import score_evaluate_P
return score_evaluate_P(tour, self.active_sizes, self.P) | python | def evaluate_tour_P(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
with better precision on the distance of the contigs.
"""
from .chic import score_evaluate_P
return score_evaluate_P(tour, self.active_sizes, self.P) | [
"def",
"evaluate_tour_P",
"(",
"self",
",",
"tour",
")",
":",
"from",
".",
"chic",
"import",
"score_evaluate_P",
"return",
"score_evaluate_P",
"(",
"tour",
",",
"self",
".",
"active_sizes",
",",
"self",
".",
"P",
")"
] | Use Cythonized version to evaluate the score of a current tour,
with better precision on the distance of the contigs. | [
"Use",
"Cythonized",
"version",
"to",
"evaluate",
"the",
"score",
"of",
"a",
"current",
"tour",
"with",
"better",
"precision",
"on",
"the",
"distance",
"of",
"the",
"contigs",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L268-L273 | train | 200,471 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.evaluate_tour_Q | def evaluate_tour_Q(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
taking orientation into consideration. This may be the most accurate
evaluation under the right condition.
"""
from .chic import score_evaluate_Q
return score_evaluate_Q(tour, self.active_sizes, self.Q) | python | def evaluate_tour_Q(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
taking orientation into consideration. This may be the most accurate
evaluation under the right condition.
"""
from .chic import score_evaluate_Q
return score_evaluate_Q(tour, self.active_sizes, self.Q) | [
"def",
"evaluate_tour_Q",
"(",
"self",
",",
"tour",
")",
":",
"from",
".",
"chic",
"import",
"score_evaluate_Q",
"return",
"score_evaluate_Q",
"(",
"tour",
",",
"self",
".",
"active_sizes",
",",
"self",
".",
"Q",
")"
] | Use Cythonized version to evaluate the score of a current tour,
taking orientation into consideration. This may be the most accurate
evaluation under the right condition. | [
"Use",
"Cythonized",
"version",
"to",
"evaluate",
"the",
"score",
"of",
"a",
"current",
"tour",
"taking",
"orientation",
"into",
"consideration",
".",
"This",
"may",
"be",
"the",
"most",
"accurate",
"evaluation",
"under",
"the",
"right",
"condition",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L275-L281 | train | 200,472 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.flip_all | def flip_all(self, tour):
""" Initialize the orientations based on pairwise O matrix.
"""
if self.signs is None: # First run
score = 0
else:
old_signs = self.signs[:self.N]
score, = self.evaluate_tour_Q(tour)
# Remember we cannot have ambiguous orientation code (0 or '?') here
self.signs = get_signs(self.O, validate=False, ambiguous=False)
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped >= score:
tag = ACCEPT
else:
self.signs = old_signs[:]
tag = REJECT
self.flip_log("FLIPALL", score, score_flipped, tag)
return tag | python | def flip_all(self, tour):
""" Initialize the orientations based on pairwise O matrix.
"""
if self.signs is None: # First run
score = 0
else:
old_signs = self.signs[:self.N]
score, = self.evaluate_tour_Q(tour)
# Remember we cannot have ambiguous orientation code (0 or '?') here
self.signs = get_signs(self.O, validate=False, ambiguous=False)
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped >= score:
tag = ACCEPT
else:
self.signs = old_signs[:]
tag = REJECT
self.flip_log("FLIPALL", score, score_flipped, tag)
return tag | [
"def",
"flip_all",
"(",
"self",
",",
"tour",
")",
":",
"if",
"self",
".",
"signs",
"is",
"None",
":",
"# First run",
"score",
"=",
"0",
"else",
":",
"old_signs",
"=",
"self",
".",
"signs",
"[",
":",
"self",
".",
"N",
"]",
"score",
",",
"=",
"self... | Initialize the orientations based on pairwise O matrix. | [
"Initialize",
"the",
"orientations",
"based",
"on",
"pairwise",
"O",
"matrix",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L287-L305 | train | 200,473 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.flip_whole | def flip_whole(self, tour):
""" Test flipping all contigs at the same time to see if score improves.
"""
score, = self.evaluate_tour_Q(tour)
self.signs = -self.signs
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped > score:
tag = ACCEPT
else:
self.signs = -self.signs
tag = REJECT
self.flip_log("FLIPWHOLE", score, score_flipped, tag)
return tag | python | def flip_whole(self, tour):
""" Test flipping all contigs at the same time to see if score improves.
"""
score, = self.evaluate_tour_Q(tour)
self.signs = -self.signs
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped > score:
tag = ACCEPT
else:
self.signs = -self.signs
tag = REJECT
self.flip_log("FLIPWHOLE", score, score_flipped, tag)
return tag | [
"def",
"flip_whole",
"(",
"self",
",",
"tour",
")",
":",
"score",
",",
"=",
"self",
".",
"evaluate_tour_Q",
"(",
"tour",
")",
"self",
".",
"signs",
"=",
"-",
"self",
".",
"signs",
"score_flipped",
",",
"=",
"self",
".",
"evaluate_tour_Q",
"(",
"tour",
... | Test flipping all contigs at the same time to see if score improves. | [
"Test",
"flipping",
"all",
"contigs",
"at",
"the",
"same",
"time",
"to",
"see",
"if",
"score",
"improves",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L307-L319 | train | 200,474 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.flip_one | def flip_one(self, tour):
""" Test flipping every single contig sequentially to see if score
improves.
"""
n_accepts = n_rejects = 0
any_tag_ACCEPT = False
for i, t in enumerate(tour):
if i == 0:
score, = self.evaluate_tour_Q(tour)
self.signs[t] = -self.signs[t]
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped > score:
n_accepts += 1
tag = ACCEPT
else:
self.signs[t] = -self.signs[t]
n_rejects += 1
tag = REJECT
self.flip_log("FLIPONE ({}/{})".format(i + 1, len(self.signs)),
score, score_flipped, tag)
if tag == ACCEPT:
any_tag_ACCEPT = True
score = score_flipped
logging.debug("FLIPONE: N_accepts={} N_rejects={}"
.format(n_accepts, n_rejects))
return ACCEPT if any_tag_ACCEPT else REJECT | python | def flip_one(self, tour):
""" Test flipping every single contig sequentially to see if score
improves.
"""
n_accepts = n_rejects = 0
any_tag_ACCEPT = False
for i, t in enumerate(tour):
if i == 0:
score, = self.evaluate_tour_Q(tour)
self.signs[t] = -self.signs[t]
score_flipped, = self.evaluate_tour_Q(tour)
if score_flipped > score:
n_accepts += 1
tag = ACCEPT
else:
self.signs[t] = -self.signs[t]
n_rejects += 1
tag = REJECT
self.flip_log("FLIPONE ({}/{})".format(i + 1, len(self.signs)),
score, score_flipped, tag)
if tag == ACCEPT:
any_tag_ACCEPT = True
score = score_flipped
logging.debug("FLIPONE: N_accepts={} N_rejects={}"
.format(n_accepts, n_rejects))
return ACCEPT if any_tag_ACCEPT else REJECT | [
"def",
"flip_one",
"(",
"self",
",",
"tour",
")",
":",
"n_accepts",
"=",
"n_rejects",
"=",
"0",
"any_tag_ACCEPT",
"=",
"False",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"tour",
")",
":",
"if",
"i",
"==",
"0",
":",
"score",
",",
"=",
"self",
... | Test flipping every single contig sequentially to see if score
improves. | [
"Test",
"flipping",
"every",
"single",
"contig",
"sequentially",
"to",
"see",
"if",
"score",
"improves",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L321-L346 | train | 200,475 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.prune_tour | def prune_tour(self, tour, cpus):
""" Test deleting each contig and check the delta_score; tour here must
be an array of ints.
"""
while True:
tour_score, = self.evaluate_tour_M(tour)
logging.debug("Starting score: {}".format(tour_score))
active_sizes = self.active_sizes
M = self.M
args = []
for i, t in enumerate(tour):
stour = tour[:i] + tour[i + 1:]
args.append((t, stour, tour_score, active_sizes, M))
# Parallel run
p = Pool(processes=cpus)
results = list(p.imap(prune_tour_worker, args))
assert len(tour) == len(results), \
"Array size mismatch, tour({}) != results({})"\
.format(len(tour), len(results))
# Identify outliers
active_contigs = self.active_contigs
idx, log10deltas = zip(*results)
lb, ub = outlier_cutoff(log10deltas)
logging.debug("Log10(delta_score) ~ [{}, {}]".format(lb, ub))
remove = set(active_contigs[x] for (x, d) in results if d < lb)
self.active -= remove
self.report_active()
tig_to_idx = self.tig_to_idx
tour = [active_contigs[x] for x in tour]
tour = array.array('i', [tig_to_idx[x] for x in tour
if x not in remove])
if not remove:
break
self.tour = tour
self.flip_all(tour)
return tour | python | def prune_tour(self, tour, cpus):
""" Test deleting each contig and check the delta_score; tour here must
be an array of ints.
"""
while True:
tour_score, = self.evaluate_tour_M(tour)
logging.debug("Starting score: {}".format(tour_score))
active_sizes = self.active_sizes
M = self.M
args = []
for i, t in enumerate(tour):
stour = tour[:i] + tour[i + 1:]
args.append((t, stour, tour_score, active_sizes, M))
# Parallel run
p = Pool(processes=cpus)
results = list(p.imap(prune_tour_worker, args))
assert len(tour) == len(results), \
"Array size mismatch, tour({}) != results({})"\
.format(len(tour), len(results))
# Identify outliers
active_contigs = self.active_contigs
idx, log10deltas = zip(*results)
lb, ub = outlier_cutoff(log10deltas)
logging.debug("Log10(delta_score) ~ [{}, {}]".format(lb, ub))
remove = set(active_contigs[x] for (x, d) in results if d < lb)
self.active -= remove
self.report_active()
tig_to_idx = self.tig_to_idx
tour = [active_contigs[x] for x in tour]
tour = array.array('i', [tig_to_idx[x] for x in tour
if x not in remove])
if not remove:
break
self.tour = tour
self.flip_all(tour)
return tour | [
"def",
"prune_tour",
"(",
"self",
",",
"tour",
",",
"cpus",
")",
":",
"while",
"True",
":",
"tour_score",
",",
"=",
"self",
".",
"evaluate_tour_M",
"(",
"tour",
")",
"logging",
".",
"debug",
"(",
"\"Starting score: {}\"",
".",
"format",
"(",
"tour_score",
... | Test deleting each contig and check the delta_score; tour here must
be an array of ints. | [
"Test",
"deleting",
"each",
"contig",
"and",
"check",
"the",
"delta_score",
";",
"tour",
"here",
"must",
"be",
"an",
"array",
"of",
"ints",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L348-L389 | train | 200,476 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.M | def M(self):
"""
Contact frequency matrix. Each cell contains how many inter-contig
links between i-th and j-th contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
M = np.zeros((N, N), dtype=int)
for (at, bt), links in self.contacts.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
M[ai, bi] = M[bi, ai] = links
return M | python | def M(self):
"""
Contact frequency matrix. Each cell contains how many inter-contig
links between i-th and j-th contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
M = np.zeros((N, N), dtype=int)
for (at, bt), links in self.contacts.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
M[ai, bi] = M[bi, ai] = links
return M | [
"def",
"M",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"N",
"tig_to_idx",
"=",
"self",
".",
"tig_to_idx",
"M",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"N",
")",
",",
"dtype",
"=",
"int",
")",
"for",
"(",
"at",
",",
"bt",
")",
",",
... | Contact frequency matrix. Each cell contains how many inter-contig
links between i-th and j-th contigs. | [
"Contact",
"frequency",
"matrix",
".",
"Each",
"cell",
"contains",
"how",
"many",
"inter",
"-",
"contig",
"links",
"between",
"i",
"-",
"th",
"and",
"j",
"-",
"th",
"contigs",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L412-L426 | train | 200,477 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.O | def O(self):
"""
Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1.
"""
N = self.N
tig_to_idx = self.tig_to_idx
O = np.zeros((N, N), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
score = strandedness * md
O[ai, bi] = O[bi, ai] = score
return O | python | def O(self):
"""
Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1.
"""
N = self.N
tig_to_idx = self.tig_to_idx
O = np.zeros((N, N), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
score = strandedness * md
O[ai, bi] = O[bi, ai] = score
return O | [
"def",
"O",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"N",
"tig_to_idx",
"=",
"self",
".",
"tig_to_idx",
"O",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"N",
")",
",",
"dtype",
"=",
"int",
")",
"for",
"(",
"at",
",",
"bt",
")",
",",
... | Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1. | [
"Pairwise",
"strandedness",
"matrix",
".",
"Each",
"cell",
"contains",
"whether",
"i",
"-",
"th",
"and",
"j",
"-",
"th",
"contig",
"are",
"the",
"same",
"orientation",
"+",
"1",
"or",
"opposite",
"orientation",
"-",
"1",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L429-L444 | train | 200,478 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.P | def P(self):
"""
Contact frequency matrix with better precision on distance between
contigs. In the matrix M, the distance is assumed to be the distance
between mid-points of two contigs. In matrix Q, however, we compute
harmonic mean of the links for the orientation configuration that is
shortest. This offers better precision for the distance between big
contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
P = np.zeros((N, N, 2), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
P[ai, bi, 0] = P[bi, ai, 0] = md
P[ai, bi, 1] = P[bi, ai, 1] = mh
return P | python | def P(self):
"""
Contact frequency matrix with better precision on distance between
contigs. In the matrix M, the distance is assumed to be the distance
between mid-points of two contigs. In matrix Q, however, we compute
harmonic mean of the links for the orientation configuration that is
shortest. This offers better precision for the distance between big
contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
P = np.zeros((N, N, 2), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
P[ai, bi, 0] = P[bi, ai, 0] = md
P[ai, bi, 1] = P[bi, ai, 1] = mh
return P | [
"def",
"P",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"N",
"tig_to_idx",
"=",
"self",
".",
"tig_to_idx",
"P",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"N",
",",
"2",
")",
",",
"dtype",
"=",
"int",
")",
"for",
"(",
"at",
",",
"bt",
... | Contact frequency matrix with better precision on distance between
contigs. In the matrix M, the distance is assumed to be the distance
between mid-points of two contigs. In matrix Q, however, we compute
harmonic mean of the links for the orientation configuration that is
shortest. This offers better precision for the distance between big
contigs. | [
"Contact",
"frequency",
"matrix",
"with",
"better",
"precision",
"on",
"distance",
"between",
"contigs",
".",
"In",
"the",
"matrix",
"M",
"the",
"distance",
"is",
"assumed",
"to",
"be",
"the",
"distance",
"between",
"mid",
"-",
"points",
"of",
"two",
"contig... | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L447-L466 | train | 200,479 |
tanghaibao/jcvi | jcvi/assembly/hic.py | CLMFile.Q | def Q(self):
"""
Contact frequency matrix when contigs are already oriented. This is s a
similar matrix as M, but rather than having the number of links in the
cell, it points to an array that has the actual distances.
"""
N = self.N
tig_to_idx = self.tig_to_idx
signs = self.signs
Q = np.ones((N, N, BB), dtype=int) * -1 # Use -1 as the sentinel
for (at, bt), k in self.contacts_oriented.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
ao = signs[ai]
bo = signs[bi]
Q[ai, bi] = k[(ao, bo)]
return Q | python | def Q(self):
"""
Contact frequency matrix when contigs are already oriented. This is s a
similar matrix as M, but rather than having the number of links in the
cell, it points to an array that has the actual distances.
"""
N = self.N
tig_to_idx = self.tig_to_idx
signs = self.signs
Q = np.ones((N, N, BB), dtype=int) * -1 # Use -1 as the sentinel
for (at, bt), k in self.contacts_oriented.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
ao = signs[ai]
bo = signs[bi]
Q[ai, bi] = k[(ao, bo)]
return Q | [
"def",
"Q",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"N",
"tig_to_idx",
"=",
"self",
".",
"tig_to_idx",
"signs",
"=",
"self",
".",
"signs",
"Q",
"=",
"np",
".",
"ones",
"(",
"(",
"N",
",",
"N",
",",
"BB",
")",
",",
"dtype",
"=",
"int",
... | Contact frequency matrix when contigs are already oriented. This is s a
similar matrix as M, but rather than having the number of links in the
cell, it points to an array that has the actual distances. | [
"Contact",
"frequency",
"matrix",
"when",
"contigs",
"are",
"already",
"oriented",
".",
"This",
"is",
"s",
"a",
"similar",
"matrix",
"as",
"M",
"but",
"rather",
"than",
"having",
"the",
"number",
"of",
"links",
"in",
"the",
"cell",
"it",
"points",
"to",
... | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L469-L487 | train | 200,480 |
tanghaibao/jcvi | jcvi/projects/ies.py | insertionpairs | def insertionpairs(args):
"""
%prog insertionpairs endpoints.bed
Pair up the candidate endpoints. A candidate exision point would contain
both left-end (LE) and right-end (RE) within a given distance.
-----------| |------------
-------| |--------
---------| |----------
(RE) (LE)
"""
p = OptionParser(insertionpairs.__doc__)
p.add_option("--extend", default=10, type="int",
help="Allow insertion sites to match up within distance")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
mergedbedfile = mergeBed(bedfile, d=opts.extend, nms=True)
bed = Bed(mergedbedfile)
fw = must_open(opts.outfile, "w")
support = lambda x: -x.reads
for b in bed:
names = b.accn.split(",")
ends = [EndPoint(x) for x in names]
REs = sorted([x for x in ends if x.leftright == "RE"], key=support)
LEs = sorted([x for x in ends if x.leftright == "LE"], key=support)
if not (REs and LEs):
continue
mRE, mLE = REs[0], LEs[0]
pRE, pLE = mRE.position, mLE.position
if pLE < pRE:
b.start, b.end = pLE - 1, pRE
else:
b.start, b.end = pRE - 1, pLE
b.accn = "{0}|{1}".format(mRE.label, mLE.label)
b.score = pLE - pRE - 1
print(b, file=fw) | python | def insertionpairs(args):
"""
%prog insertionpairs endpoints.bed
Pair up the candidate endpoints. A candidate exision point would contain
both left-end (LE) and right-end (RE) within a given distance.
-----------| |------------
-------| |--------
---------| |----------
(RE) (LE)
"""
p = OptionParser(insertionpairs.__doc__)
p.add_option("--extend", default=10, type="int",
help="Allow insertion sites to match up within distance")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
mergedbedfile = mergeBed(bedfile, d=opts.extend, nms=True)
bed = Bed(mergedbedfile)
fw = must_open(opts.outfile, "w")
support = lambda x: -x.reads
for b in bed:
names = b.accn.split(",")
ends = [EndPoint(x) for x in names]
REs = sorted([x for x in ends if x.leftright == "RE"], key=support)
LEs = sorted([x for x in ends if x.leftright == "LE"], key=support)
if not (REs and LEs):
continue
mRE, mLE = REs[0], LEs[0]
pRE, pLE = mRE.position, mLE.position
if pLE < pRE:
b.start, b.end = pLE - 1, pRE
else:
b.start, b.end = pRE - 1, pLE
b.accn = "{0}|{1}".format(mRE.label, mLE.label)
b.score = pLE - pRE - 1
print(b, file=fw) | [
"def",
"insertionpairs",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"insertionpairs",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--extend\"",
",",
"default",
"=",
"10",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Allow insertion ... | %prog insertionpairs endpoints.bed
Pair up the candidate endpoints. A candidate exision point would contain
both left-end (LE) and right-end (RE) within a given distance.
-----------| |------------
-------| |--------
---------| |----------
(RE) (LE) | [
"%prog",
"insertionpairs",
"endpoints",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/ies.py#L164-L205 | train | 200,481 |
tanghaibao/jcvi | jcvi/projects/ies.py | insertion | def insertion(args):
"""
%prog insertion mic.mac.bed
Find IES based on mapping MIC reads to MAC genome. Output a bedfile with
'lesions' (stack of broken reads) in the MAC genome.
"""
p = OptionParser(insertion.__doc__)
p.add_option("--mindepth", default=6, type="int",
help="Minimum depth to call an insertion")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
mindepth = opts.mindepth
bed = Bed(bedfile)
fw = must_open(opts.outfile, "w")
for seqid, feats in bed.sub_beds():
left_ends = Counter([x.start for x in feats])
right_ends = Counter([x.end for x in feats])
selected = []
for le, count in left_ends.items():
if count >= mindepth:
selected.append((seqid, le, "LE-{0}".format(le), count))
for re, count in right_ends.items():
if count >= mindepth:
selected.append((seqid, re, "RE-{0}".format(re), count))
selected.sort()
for seqid, pos, label, count in selected:
label = "{0}-r{1}".format(label, count)
print("\t".join((seqid, str(pos - 1), str(pos), label)), file=fw) | python | def insertion(args):
"""
%prog insertion mic.mac.bed
Find IES based on mapping MIC reads to MAC genome. Output a bedfile with
'lesions' (stack of broken reads) in the MAC genome.
"""
p = OptionParser(insertion.__doc__)
p.add_option("--mindepth", default=6, type="int",
help="Minimum depth to call an insertion")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
mindepth = opts.mindepth
bed = Bed(bedfile)
fw = must_open(opts.outfile, "w")
for seqid, feats in bed.sub_beds():
left_ends = Counter([x.start for x in feats])
right_ends = Counter([x.end for x in feats])
selected = []
for le, count in left_ends.items():
if count >= mindepth:
selected.append((seqid, le, "LE-{0}".format(le), count))
for re, count in right_ends.items():
if count >= mindepth:
selected.append((seqid, re, "RE-{0}".format(re), count))
selected.sort()
for seqid, pos, label, count in selected:
label = "{0}-r{1}".format(label, count)
print("\t".join((seqid, str(pos - 1), str(pos), label)), file=fw) | [
"def",
"insertion",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"insertion",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mindepth\"",
",",
"default",
"=",
"6",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Minimum depth to call an ... | %prog insertion mic.mac.bed
Find IES based on mapping MIC reads to MAC genome. Output a bedfile with
'lesions' (stack of broken reads) in the MAC genome. | [
"%prog",
"insertion",
"mic",
".",
"mac",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/ies.py#L208-L241 | train | 200,482 |
tanghaibao/jcvi | jcvi/assembly/sim.py | add_sim_options | def add_sim_options(p):
"""
Add options shared by eagle or wgsim.
"""
p.add_option("--distance", default=500, type="int",
help="Outer distance between the two ends [default: %default]")
p.add_option("--readlen", default=150, type="int",
help="Length of the read")
p.set_depth(depth=10)
p.set_outfile(outfile=None) | python | def add_sim_options(p):
"""
Add options shared by eagle or wgsim.
"""
p.add_option("--distance", default=500, type="int",
help="Outer distance between the two ends [default: %default]")
p.add_option("--readlen", default=150, type="int",
help="Length of the read")
p.set_depth(depth=10)
p.set_outfile(outfile=None) | [
"def",
"add_sim_options",
"(",
"p",
")",
":",
"p",
".",
"add_option",
"(",
"\"--distance\"",
",",
"default",
"=",
"500",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Outer distance between the two ends [default: %default]\"",
")",
"p",
".",
"add_option",
"(... | Add options shared by eagle or wgsim. | [
"Add",
"options",
"shared",
"by",
"eagle",
"or",
"wgsim",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/sim.py#L31-L40 | train | 200,483 |
tanghaibao/jcvi | jcvi/assembly/sim.py | wgsim | def wgsim(args):
"""
%prog wgsim fastafile
Run dwgsim on fastafile.
"""
p = OptionParser(wgsim.__doc__)
p.add_option("--erate", default=.01, type="float",
help="Base error rate of the read [default: %default]")
p.add_option("--noerrors", default=False, action="store_true",
help="Simulate reads with no errors [default: %default]")
p.add_option("--genomesize", type="int",
help="Genome size in Mb [default: estimate from data]")
add_sim_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
pf = op.basename(fastafile).split(".")[0]
genomesize = opts.genomesize
size = genomesize * 1000000 if genomesize else Fasta(fastafile).totalsize
depth = opts.depth
readlen = opts.readlen
readnum = int(math.ceil(size * depth / (2 * readlen)))
distance = opts.distance
stdev = distance / 10
outpf = opts.outfile or "{0}.{1}bp.{2}x".format(pf, distance, depth)
logging.debug("Total genome size: {0} bp".format(size))
logging.debug("Target depth: {0}x".format(depth))
logging.debug("Number of read pairs (2x{0}): {1}".format(readlen, readnum))
if opts.noerrors:
opts.erate = 0
cmd = "dwgsim -e {0} -E {0}".format(opts.erate)
if opts.noerrors:
cmd += " -r 0 -R 0 -X 0 -y 0"
cmd += " -d {0} -s {1}".format(distance, stdev)
cmd += " -N {0} -1 {1} -2 {1}".format(readnum, readlen)
cmd += " {0} {1}".format(fastafile, outpf)
sh(cmd) | python | def wgsim(args):
"""
%prog wgsim fastafile
Run dwgsim on fastafile.
"""
p = OptionParser(wgsim.__doc__)
p.add_option("--erate", default=.01, type="float",
help="Base error rate of the read [default: %default]")
p.add_option("--noerrors", default=False, action="store_true",
help="Simulate reads with no errors [default: %default]")
p.add_option("--genomesize", type="int",
help="Genome size in Mb [default: estimate from data]")
add_sim_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
pf = op.basename(fastafile).split(".")[0]
genomesize = opts.genomesize
size = genomesize * 1000000 if genomesize else Fasta(fastafile).totalsize
depth = opts.depth
readlen = opts.readlen
readnum = int(math.ceil(size * depth / (2 * readlen)))
distance = opts.distance
stdev = distance / 10
outpf = opts.outfile or "{0}.{1}bp.{2}x".format(pf, distance, depth)
logging.debug("Total genome size: {0} bp".format(size))
logging.debug("Target depth: {0}x".format(depth))
logging.debug("Number of read pairs (2x{0}): {1}".format(readlen, readnum))
if opts.noerrors:
opts.erate = 0
cmd = "dwgsim -e {0} -E {0}".format(opts.erate)
if opts.noerrors:
cmd += " -r 0 -R 0 -X 0 -y 0"
cmd += " -d {0} -s {1}".format(distance, stdev)
cmd += " -N {0} -1 {1} -2 {1}".format(readnum, readlen)
cmd += " {0} {1}".format(fastafile, outpf)
sh(cmd) | [
"def",
"wgsim",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"wgsim",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--erate\"",
",",
"default",
"=",
".01",
",",
"type",
"=",
"\"float\"",
",",
"help",
"=",
"\"Base error rate of the read [def... | %prog wgsim fastafile
Run dwgsim on fastafile. | [
"%prog",
"wgsim",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/sim.py#L142-L189 | train | 200,484 |
tanghaibao/jcvi | jcvi/projects/napus.py | fig4 | def fig4(args):
"""
%prog fig4 layout data
Napus Figure 4A displays an example deleted region for quartet chromosomes,
showing read alignments from high GL and low GL lines.
"""
p = OptionParser(fig4.__doc__)
p.add_option("--gauge_step", default=200000, type="int",
help="Step size for the base scale")
opts, args, iopts = p.set_image_options(args, figsize="9x7")
if len(args) != 2:
sys.exit(not p.print_help())
layout, datadir = args
layout = F4ALayout(layout, datadir=datadir)
gs = opts.gauge_step
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
block, napusbed, slayout = "r28.txt", "all.bed", "r28.layout"
s = Synteny(fig, root, block, napusbed, slayout, chr_label=False)
synteny_exts = [(x.xstart, x.xend) for x in s.rr]
h = .1
order = "bzh,yudal".split(",")
labels = (r"\textit{B. napus} A$\mathsf{_n}$2",
r"\textit{B. rapa} A$\mathsf{_r}$2",
r"\textit{B. oleracea} C$\mathsf{_o}$2",
r"\textit{B. napus} C$\mathsf{_n}$2")
for t in layout:
xstart, xend = synteny_exts[2 * t.i]
canvas = [xstart, t.y, xend - xstart, h]
root.text(xstart - h, t.y + h / 2, labels[t.i], ha="center", va="center")
ch, ab = t.box_region.split(":")
a, b = ab.split("-")
vlines = [int(x) for x in (a, b)]
Coverage(fig, root, canvas, t.seqid, (t.start, t.end), datadir,
order=order, gauge="top", plot_chr_label=False,
gauge_step=gs, palette="gray",
cap=40, hlsuffix="regions.forhaibao",
vlines=vlines)
# Highlight GSL biosynthesis genes
a, b = (3, "Bra029311"), (5, "Bo2g161590")
for gid in (a, b):
start, end = s.gg[gid]
xstart, ystart = start
xend, yend = end
x = (xstart + xend) / 2
arrow = FancyArrowPatch(posA=(x, ystart - .04),
posB=(x, ystart - .005),
arrowstyle="fancy,head_width=6,head_length=8",
lw=3, fc='k', ec='k', zorder=20)
root.add_patch(arrow)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
image_name = "napus-fig4." + iopts.format
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | python | def fig4(args):
"""
%prog fig4 layout data
Napus Figure 4A displays an example deleted region for quartet chromosomes,
showing read alignments from high GL and low GL lines.
"""
p = OptionParser(fig4.__doc__)
p.add_option("--gauge_step", default=200000, type="int",
help="Step size for the base scale")
opts, args, iopts = p.set_image_options(args, figsize="9x7")
if len(args) != 2:
sys.exit(not p.print_help())
layout, datadir = args
layout = F4ALayout(layout, datadir=datadir)
gs = opts.gauge_step
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
block, napusbed, slayout = "r28.txt", "all.bed", "r28.layout"
s = Synteny(fig, root, block, napusbed, slayout, chr_label=False)
synteny_exts = [(x.xstart, x.xend) for x in s.rr]
h = .1
order = "bzh,yudal".split(",")
labels = (r"\textit{B. napus} A$\mathsf{_n}$2",
r"\textit{B. rapa} A$\mathsf{_r}$2",
r"\textit{B. oleracea} C$\mathsf{_o}$2",
r"\textit{B. napus} C$\mathsf{_n}$2")
for t in layout:
xstart, xend = synteny_exts[2 * t.i]
canvas = [xstart, t.y, xend - xstart, h]
root.text(xstart - h, t.y + h / 2, labels[t.i], ha="center", va="center")
ch, ab = t.box_region.split(":")
a, b = ab.split("-")
vlines = [int(x) for x in (a, b)]
Coverage(fig, root, canvas, t.seqid, (t.start, t.end), datadir,
order=order, gauge="top", plot_chr_label=False,
gauge_step=gs, palette="gray",
cap=40, hlsuffix="regions.forhaibao",
vlines=vlines)
# Highlight GSL biosynthesis genes
a, b = (3, "Bra029311"), (5, "Bo2g161590")
for gid in (a, b):
start, end = s.gg[gid]
xstart, ystart = start
xend, yend = end
x = (xstart + xend) / 2
arrow = FancyArrowPatch(posA=(x, ystart - .04),
posB=(x, ystart - .005),
arrowstyle="fancy,head_width=6,head_length=8",
lw=3, fc='k', ec='k', zorder=20)
root.add_patch(arrow)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
image_name = "napus-fig4." + iopts.format
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | [
"def",
"fig4",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fig4",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gauge_step\"",
",",
"default",
"=",
"200000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Step size for the base scale... | %prog fig4 layout data
Napus Figure 4A displays an example deleted region for quartet chromosomes,
showing read alignments from high GL and low GL lines. | [
"%prog",
"fig4",
"layout",
"data"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/napus.py#L415-L478 | train | 200,485 |
tanghaibao/jcvi | jcvi/projects/napus.py | ploidy | def ploidy(args):
"""
%prog ploidy seqids layout
Build a figure that calls graphics.karyotype to illustrate the high ploidy
of B. napus genome.
"""
p = OptionParser(ploidy.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x7")
if len(args) != 2:
sys.exit(not p.print_help())
seqidsfile, klayout = args
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
Karyotype(fig, root, seqidsfile, klayout)
fc = "darkslategrey"
radius = .012
ot = -.05 # use this to adjust vertical position of the left panel
TextCircle(root, .1, .9 + ot, r'$\gamma$', radius=radius, fc=fc)
root.text(.1, .88 + ot, r"$\times3$", ha="center", va="top", color=fc)
TextCircle(root, .08, .79 + ot, r'$\alpha$', radius=radius, fc=fc)
TextCircle(root, .12, .79 + ot, r'$\beta$', radius=radius, fc=fc)
root.text(.1, .77 + ot, r"$\times3\times2\times2$", ha="center", va="top", color=fc)
root.text(.1, .67 + ot, r"Brassica triplication", ha="center",
va="top", color=fc, size=11)
root.text(.1, .65 + ot, r"$\times3\times2\times2\times3$", ha="center", va="top", color=fc)
root.text(.1, .42 + ot, r"Allo-tetraploidy", ha="center",
va="top", color=fc, size=11)
root.text(.1, .4 + ot, r"$\times3\times2\times2\times3\times2$", ha="center", va="top", color=fc)
bb = dict(boxstyle="round,pad=.5", fc="w", ec="0.5", alpha=0.5)
root.text(.5, .2 + ot, r"\noindent\textit{Brassica napus}\\"
"(A$\mathsf{_n}$C$\mathsf{_n}$ genome)", ha="center",
size=16, color="k", bbox=bb)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
pf = "napus"
image_name = pf + "." + iopts.format
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | python | def ploidy(args):
"""
%prog ploidy seqids layout
Build a figure that calls graphics.karyotype to illustrate the high ploidy
of B. napus genome.
"""
p = OptionParser(ploidy.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x7")
if len(args) != 2:
sys.exit(not p.print_help())
seqidsfile, klayout = args
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
Karyotype(fig, root, seqidsfile, klayout)
fc = "darkslategrey"
radius = .012
ot = -.05 # use this to adjust vertical position of the left panel
TextCircle(root, .1, .9 + ot, r'$\gamma$', radius=radius, fc=fc)
root.text(.1, .88 + ot, r"$\times3$", ha="center", va="top", color=fc)
TextCircle(root, .08, .79 + ot, r'$\alpha$', radius=radius, fc=fc)
TextCircle(root, .12, .79 + ot, r'$\beta$', radius=radius, fc=fc)
root.text(.1, .77 + ot, r"$\times3\times2\times2$", ha="center", va="top", color=fc)
root.text(.1, .67 + ot, r"Brassica triplication", ha="center",
va="top", color=fc, size=11)
root.text(.1, .65 + ot, r"$\times3\times2\times2\times3$", ha="center", va="top", color=fc)
root.text(.1, .42 + ot, r"Allo-tetraploidy", ha="center",
va="top", color=fc, size=11)
root.text(.1, .4 + ot, r"$\times3\times2\times2\times3\times2$", ha="center", va="top", color=fc)
bb = dict(boxstyle="round,pad=.5", fc="w", ec="0.5", alpha=0.5)
root.text(.5, .2 + ot, r"\noindent\textit{Brassica napus}\\"
"(A$\mathsf{_n}$C$\mathsf{_n}$ genome)", ha="center",
size=16, color="k", bbox=bb)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
pf = "napus"
image_name = pf + "." + iopts.format
savefig(image_name, dpi=iopts.dpi, iopts=iopts) | [
"def",
"ploidy",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"ploidy",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
",",
"figsize",
"=",
"\"8x7\"",
")",
"if",
"len",
"(",
"args",
... | %prog ploidy seqids layout
Build a figure that calls graphics.karyotype to illustrate the high ploidy
of B. napus genome. | [
"%prog",
"ploidy",
"seqids",
"layout"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/napus.py#L558-L604 | train | 200,486 |
tanghaibao/jcvi | jcvi/assembly/patch.py | pasteprepare | def pasteprepare(args):
"""
%prog pasteprepare bacs.fasta
Prepare sequences for paste.
"""
p = OptionParser(pasteprepare.__doc__)
p.add_option("--flank", default=5000, type="int",
help="Get the seq of size on two ends [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
goodfasta, = args
flank = opts.flank
pf = goodfasta.rsplit(".", 1)[0]
extbed = pf + ".ext.bed"
sizes = Sizes(goodfasta)
fw = open(extbed, "w")
for bac, size in sizes.iter_sizes():
print("\t".join(str(x) for x in \
(bac, 0, min(flank, size), bac + "L")), file=fw)
print("\t".join(str(x) for x in \
(bac, max(size - flank, 0), size, bac + "R")), file=fw)
fw.close()
fastaFromBed(extbed, goodfasta, name=True) | python | def pasteprepare(args):
"""
%prog pasteprepare bacs.fasta
Prepare sequences for paste.
"""
p = OptionParser(pasteprepare.__doc__)
p.add_option("--flank", default=5000, type="int",
help="Get the seq of size on two ends [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
goodfasta, = args
flank = opts.flank
pf = goodfasta.rsplit(".", 1)[0]
extbed = pf + ".ext.bed"
sizes = Sizes(goodfasta)
fw = open(extbed, "w")
for bac, size in sizes.iter_sizes():
print("\t".join(str(x) for x in \
(bac, 0, min(flank, size), bac + "L")), file=fw)
print("\t".join(str(x) for x in \
(bac, max(size - flank, 0), size, bac + "R")), file=fw)
fw.close()
fastaFromBed(extbed, goodfasta, name=True) | [
"def",
"pasteprepare",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"pasteprepare",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--flank\"",
",",
"default",
"=",
"5000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Get the seq of size... | %prog pasteprepare bacs.fasta
Prepare sequences for paste. | [
"%prog",
"pasteprepare",
"bacs",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L174-L202 | train | 200,487 |
tanghaibao/jcvi | jcvi/assembly/patch.py | paste | def paste(args):
"""
%prog paste flanks.bed flanks_vs_assembly.blast backbone.fasta
Paste in good sequences in the final assembly.
"""
from jcvi.formats.bed import uniq
p = OptionParser(paste.__doc__)
p.add_option("--maxsize", default=300000, type="int",
help="Maximum size of patchers to be replaced [default: %default]")
p.add_option("--prefix", help="Prefix of the new object [default: %default]")
p.set_rclip(rclip=1)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
pbed, blastfile, bbfasta = args
maxsize = opts.maxsize # Max DNA size to replace gap
order = Bed(pbed).order
beforebed, afterbed = blast_to_twobeds(blastfile, order, log=True,
rclip=opts.rclip, maxsize=maxsize,
flipbeds=True)
beforebed = uniq([beforebed])
afbed = Bed(beforebed)
bfbed = Bed(afterbed)
shuffle_twobeds(afbed, bfbed, bbfasta, prefix=opts.prefix) | python | def paste(args):
"""
%prog paste flanks.bed flanks_vs_assembly.blast backbone.fasta
Paste in good sequences in the final assembly.
"""
from jcvi.formats.bed import uniq
p = OptionParser(paste.__doc__)
p.add_option("--maxsize", default=300000, type="int",
help="Maximum size of patchers to be replaced [default: %default]")
p.add_option("--prefix", help="Prefix of the new object [default: %default]")
p.set_rclip(rclip=1)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
pbed, blastfile, bbfasta = args
maxsize = opts.maxsize # Max DNA size to replace gap
order = Bed(pbed).order
beforebed, afterbed = blast_to_twobeds(blastfile, order, log=True,
rclip=opts.rclip, maxsize=maxsize,
flipbeds=True)
beforebed = uniq([beforebed])
afbed = Bed(beforebed)
bfbed = Bed(afterbed)
shuffle_twobeds(afbed, bfbed, bbfasta, prefix=opts.prefix) | [
"def",
"paste",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"uniq",
"p",
"=",
"OptionParser",
"(",
"paste",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--maxsize\"",
",",
"default",
"=",
"300000",
",",
"type",
... | %prog paste flanks.bed flanks_vs_assembly.blast backbone.fasta
Paste in good sequences in the final assembly. | [
"%prog",
"paste",
"flanks",
".",
"bed",
"flanks_vs_assembly",
".",
"blast",
"backbone",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L205-L235 | train | 200,488 |
tanghaibao/jcvi | jcvi/assembly/patch.py | eject | def eject(args):
"""
%prog eject candidates.bed chr.fasta
Eject scaffolds from assembly, using the range identified by closest().
"""
p = OptionParser(eject.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
candidates, chrfasta = args
sizesfile = Sizes(chrfasta).filename
cbedfile = complementBed(candidates, sizesfile)
cbed = Bed(cbedfile)
for b in cbed:
b.accn = b.seqid
b.score = 1000
b.strand = '+'
cbed.print_to_file() | python | def eject(args):
"""
%prog eject candidates.bed chr.fasta
Eject scaffolds from assembly, using the range identified by closest().
"""
p = OptionParser(eject.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
candidates, chrfasta = args
sizesfile = Sizes(chrfasta).filename
cbedfile = complementBed(candidates, sizesfile)
cbed = Bed(cbedfile)
for b in cbed:
b.accn = b.seqid
b.score = 1000
b.strand = '+'
cbed.print_to_file() | [
"def",
"eject",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"eject",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"not... | %prog eject candidates.bed chr.fasta
Eject scaffolds from assembly, using the range identified by closest(). | [
"%prog",
"eject",
"candidates",
".",
"bed",
"chr",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L238-L260 | train | 200,489 |
tanghaibao/jcvi | jcvi/assembly/patch.py | closest | def closest(args):
"""
%prog closest candidates.bed gaps.bed fastafile
Identify the nearest gaps flanking suggested regions.
"""
p = OptionParser(closest.__doc__)
p.add_option("--om", default=False, action="store_true",
help="The bedfile is OM blocks [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
candidates, gapsbed, fastafile = args
sizes = Sizes(fastafile).mapping
bed = Bed(candidates)
ranges = []
for b in bed:
r = range_parse(b.accn) if opts.om else b
ranges.append([r.seqid, r.start, r.end])
gapsbed = Bed(gapsbed)
granges = [(x.seqid, x.start, x.end) for x in gapsbed]
ranges = range_merge(ranges)
for r in ranges:
a = range_closest(granges, r)
b = range_closest(granges, r, left=False)
seqid = r[0]
if a is not None and a[0] != seqid:
a = None
if b is not None and b[0] != seqid:
b = None
mmin = 1 if a is None else a[1]
mmax = sizes[seqid] if b is None else b[2]
print("\t".join(str(x) for x in (seqid, mmin - 1, mmax))) | python | def closest(args):
"""
%prog closest candidates.bed gaps.bed fastafile
Identify the nearest gaps flanking suggested regions.
"""
p = OptionParser(closest.__doc__)
p.add_option("--om", default=False, action="store_true",
help="The bedfile is OM blocks [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
candidates, gapsbed, fastafile = args
sizes = Sizes(fastafile).mapping
bed = Bed(candidates)
ranges = []
for b in bed:
r = range_parse(b.accn) if opts.om else b
ranges.append([r.seqid, r.start, r.end])
gapsbed = Bed(gapsbed)
granges = [(x.seqid, x.start, x.end) for x in gapsbed]
ranges = range_merge(ranges)
for r in ranges:
a = range_closest(granges, r)
b = range_closest(granges, r, left=False)
seqid = r[0]
if a is not None and a[0] != seqid:
a = None
if b is not None and b[0] != seqid:
b = None
mmin = 1 if a is None else a[1]
mmax = sizes[seqid] if b is None else b[2]
print("\t".join(str(x) for x in (seqid, mmin - 1, mmax))) | [
"def",
"closest",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"closest",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--om\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"The bedfile is OM bloc... | %prog closest candidates.bed gaps.bed fastafile
Identify the nearest gaps flanking suggested regions. | [
"%prog",
"closest",
"candidates",
".",
"bed",
"gaps",
".",
"bed",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L263-L302 | train | 200,490 |
tanghaibao/jcvi | jcvi/assembly/patch.py | insert | def insert(args):
"""
%prog insert candidates.bed gaps.bed chrs.fasta unplaced.fasta
Insert scaffolds into assembly.
"""
from jcvi.formats.agp import mask, bed
from jcvi.formats.sizes import agp
p = OptionParser(insert.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
candidates, gapsbed, chrfasta, unplacedfasta = args
refinedbed = refine([candidates, gapsbed])
sizes = Sizes(unplacedfasta).mapping
cbed = Bed(candidates)
corder = cbed.order
gbed = Bed(gapsbed)
gorder = gbed.order
gpbed = Bed()
gappositions = {} # (chr, start, end) => gapid
fp = open(refinedbed)
gap_to_scf = defaultdict(list)
seen = set()
for row in fp:
atoms = row.split()
if len(atoms) <= 6:
continue
unplaced = atoms[3]
strand = atoms[5]
gapid = atoms[9]
if gapid not in seen:
seen.add(gapid)
gi, gb = gorder[gapid]
gpbed.append(gb)
gappositions[(gb.seqid, gb.start, gb.end)] = gapid
gap_to_scf[gapid].append((unplaced, strand))
gpbedfile = "candidate.gaps.bed"
gpbed.print_to_file(gpbedfile, sorted=True)
agpfile = agp([chrfasta])
maskedagpfile = mask([agpfile, gpbedfile])
maskedbedfile = maskedagpfile.rsplit(".", 1)[0] + ".bed"
bed([maskedagpfile, "--outfile={0}".format(maskedbedfile)])
mbed = Bed(maskedbedfile)
finalbed = Bed()
for b in mbed:
sid = b.seqid
key = (sid, b.start, b.end)
if key not in gappositions:
finalbed.add("{0}\n".format(b))
continue
gapid = gappositions[key]
scfs = gap_to_scf[gapid]
# For scaffolds placed in the same gap, sort according to positions
scfs.sort(key=lambda x: corder[x[0]][1].start + corder[x[0]][1].end)
for scf, strand in scfs:
size = sizes[scf]
finalbed.add("\t".join(str(x) for x in \
(scf, 0, size, sid, 1000, strand)))
finalbedfile = "final.bed"
finalbed.print_to_file(finalbedfile)
# Clean-up
toclean = [gpbedfile, agpfile, maskedagpfile, maskedbedfile]
FileShredder(toclean) | python | def insert(args):
"""
%prog insert candidates.bed gaps.bed chrs.fasta unplaced.fasta
Insert scaffolds into assembly.
"""
from jcvi.formats.agp import mask, bed
from jcvi.formats.sizes import agp
p = OptionParser(insert.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
candidates, gapsbed, chrfasta, unplacedfasta = args
refinedbed = refine([candidates, gapsbed])
sizes = Sizes(unplacedfasta).mapping
cbed = Bed(candidates)
corder = cbed.order
gbed = Bed(gapsbed)
gorder = gbed.order
gpbed = Bed()
gappositions = {} # (chr, start, end) => gapid
fp = open(refinedbed)
gap_to_scf = defaultdict(list)
seen = set()
for row in fp:
atoms = row.split()
if len(atoms) <= 6:
continue
unplaced = atoms[3]
strand = atoms[5]
gapid = atoms[9]
if gapid not in seen:
seen.add(gapid)
gi, gb = gorder[gapid]
gpbed.append(gb)
gappositions[(gb.seqid, gb.start, gb.end)] = gapid
gap_to_scf[gapid].append((unplaced, strand))
gpbedfile = "candidate.gaps.bed"
gpbed.print_to_file(gpbedfile, sorted=True)
agpfile = agp([chrfasta])
maskedagpfile = mask([agpfile, gpbedfile])
maskedbedfile = maskedagpfile.rsplit(".", 1)[0] + ".bed"
bed([maskedagpfile, "--outfile={0}".format(maskedbedfile)])
mbed = Bed(maskedbedfile)
finalbed = Bed()
for b in mbed:
sid = b.seqid
key = (sid, b.start, b.end)
if key not in gappositions:
finalbed.add("{0}\n".format(b))
continue
gapid = gappositions[key]
scfs = gap_to_scf[gapid]
# For scaffolds placed in the same gap, sort according to positions
scfs.sort(key=lambda x: corder[x[0]][1].start + corder[x[0]][1].end)
for scf, strand in scfs:
size = sizes[scf]
finalbed.add("\t".join(str(x) for x in \
(scf, 0, size, sid, 1000, strand)))
finalbedfile = "final.bed"
finalbed.print_to_file(finalbedfile)
# Clean-up
toclean = [gpbedfile, agpfile, maskedagpfile, maskedbedfile]
FileShredder(toclean) | [
"def",
"insert",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"agp",
"import",
"mask",
",",
"bed",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"agp",
"p",
"=",
"OptionParser",
"(",
"insert",
".",
"__doc__",
")",
"opts",
","... | %prog insert candidates.bed gaps.bed chrs.fasta unplaced.fasta
Insert scaffolds into assembly. | [
"%prog",
"insert",
"candidates",
".",
"bed",
"gaps",
".",
"bed",
"chrs",
".",
"fasta",
"unplaced",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L305-L380 | train | 200,491 |
tanghaibao/jcvi | jcvi/assembly/patch.py | gaps | def gaps(args):
"""
%prog gaps OM.bed fastafile
Create patches around OM gaps.
"""
from jcvi.formats.bed import uniq
from jcvi.utils.iter import pairwise
p = OptionParser(gaps.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ombed, fastafile = args
ombed = uniq([ombed])
bed = Bed(ombed)
for a, b in pairwise(bed):
om_a = (a.seqid, a.start, a.end, "+")
om_b = (b.seqid, b.start, b.end, "+")
ch_a = range_parse(a.accn)
ch_b = range_parse(b.accn)
ch_a = (ch_a.seqid, ch_a.start, ch_a.end, "+")
ch_b = (ch_b.seqid, ch_b.start, ch_b.end, "+")
om_dist, x = range_distance(om_a, om_b, distmode="ee")
ch_dist, x = range_distance(ch_a, ch_b, distmode="ee")
if om_dist <= 0 and ch_dist <= 0:
continue
print(a)
print(b)
print(om_dist, ch_dist) | python | def gaps(args):
"""
%prog gaps OM.bed fastafile
Create patches around OM gaps.
"""
from jcvi.formats.bed import uniq
from jcvi.utils.iter import pairwise
p = OptionParser(gaps.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ombed, fastafile = args
ombed = uniq([ombed])
bed = Bed(ombed)
for a, b in pairwise(bed):
om_a = (a.seqid, a.start, a.end, "+")
om_b = (b.seqid, b.start, b.end, "+")
ch_a = range_parse(a.accn)
ch_b = range_parse(b.accn)
ch_a = (ch_a.seqid, ch_a.start, ch_a.end, "+")
ch_b = (ch_b.seqid, ch_b.start, ch_b.end, "+")
om_dist, x = range_distance(om_a, om_b, distmode="ee")
ch_dist, x = range_distance(ch_a, ch_b, distmode="ee")
if om_dist <= 0 and ch_dist <= 0:
continue
print(a)
print(b)
print(om_dist, ch_dist) | [
"def",
"gaps",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"uniq",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"pairwise",
"p",
"=",
"OptionParser",
"(",
"gaps",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",... | %prog gaps OM.bed fastafile
Create patches around OM gaps. | [
"%prog",
"gaps",
"OM",
".",
"bed",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L546-L581 | train | 200,492 |
tanghaibao/jcvi | jcvi/assembly/patch.py | tips | def tips(args):
"""
%prog tips patchers.bed complements.bed original.fasta backbone.fasta
Append telomeric sequences based on patchers and complements.
"""
p = OptionParser(tips.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
pbedfile, cbedfile, sizesfile, bbfasta = args
pbed = Bed(pbedfile, sorted=False)
cbed = Bed(cbedfile, sorted=False)
complements = dict()
for object, beds in groupby(cbed, key=lambda x: x.seqid):
beds = list(beds)
complements[object] = beds
sizes = Sizes(sizesfile).mapping
bbsizes = Sizes(bbfasta).mapping
tbeds = []
for object, beds in groupby(pbed, key=lambda x: x.accn):
beds = list(beds)
startbed, endbed = beds[0], beds[-1]
start_id, end_id = startbed.seqid, endbed.seqid
if startbed.start == 1:
start_id = None
if endbed.end == sizes[end_id]:
end_id = None
print(object, start_id, end_id, file=sys.stderr)
if start_id:
b = complements[start_id][0]
b.accn = object
tbeds.append(b)
tbeds.append(BedLine("\t".join(str(x) for x in \
(object, 0, bbsizes[object], object, 1000, "+"))))
if end_id:
b = complements[end_id][-1]
b.accn = object
tbeds.append(b)
tbed = Bed()
tbed.extend(tbeds)
tbedfile = "tips.bed"
tbed.print_to_file(tbedfile) | python | def tips(args):
"""
%prog tips patchers.bed complements.bed original.fasta backbone.fasta
Append telomeric sequences based on patchers and complements.
"""
p = OptionParser(tips.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
pbedfile, cbedfile, sizesfile, bbfasta = args
pbed = Bed(pbedfile, sorted=False)
cbed = Bed(cbedfile, sorted=False)
complements = dict()
for object, beds in groupby(cbed, key=lambda x: x.seqid):
beds = list(beds)
complements[object] = beds
sizes = Sizes(sizesfile).mapping
bbsizes = Sizes(bbfasta).mapping
tbeds = []
for object, beds in groupby(pbed, key=lambda x: x.accn):
beds = list(beds)
startbed, endbed = beds[0], beds[-1]
start_id, end_id = startbed.seqid, endbed.seqid
if startbed.start == 1:
start_id = None
if endbed.end == sizes[end_id]:
end_id = None
print(object, start_id, end_id, file=sys.stderr)
if start_id:
b = complements[start_id][0]
b.accn = object
tbeds.append(b)
tbeds.append(BedLine("\t".join(str(x) for x in \
(object, 0, bbsizes[object], object, 1000, "+"))))
if end_id:
b = complements[end_id][-1]
b.accn = object
tbeds.append(b)
tbed = Bed()
tbed.extend(tbeds)
tbedfile = "tips.bed"
tbed.print_to_file(tbedfile) | [
"def",
"tips",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"tips",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"4",
":",
"sys",
".",
"exit",
"(",
"not",... | %prog tips patchers.bed complements.bed original.fasta backbone.fasta
Append telomeric sequences based on patchers and complements. | [
"%prog",
"tips",
"patchers",
".",
"bed",
"complements",
".",
"bed",
"original",
".",
"fasta",
"backbone",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L584-L634 | train | 200,493 |
tanghaibao/jcvi | jcvi/assembly/patch.py | fill | def fill(args):
"""
%prog fill gaps.bed bad.fasta
Perform gap filling of one assembly (bad) using sequences from another.
"""
p = OptionParser(fill.__doc__)
p.add_option("--extend", default=2000, type="int",
help="Extend seq flanking the gaps [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gapsbed, badfasta = args
Ext = opts.extend
gapdist = 2 * Ext + 1 # This is to prevent to replacement ranges intersect
gapsbed = mergeBed(gapsbed, d=gapdist, nms=True)
bed = Bed(gapsbed)
sizes = Sizes(badfasta).mapping
pf = gapsbed.rsplit(".", 1)[0]
extbed = pf + ".ext.bed"
fw = open(extbed, "w")
for b in bed:
gapname = b.accn
start, end = max(0, b.start - Ext - 1), b.start - 1
print("\t".join(str(x) for x in \
(b.seqid, start, end, gapname + "L")), file=fw)
start, end = b.end, min(sizes[b.seqid], b.end + Ext)
print("\t".join(str(x) for x in \
(b.seqid, start, end, gapname + "R")), file=fw)
fw.close()
fastaFromBed(extbed, badfasta, name=True) | python | def fill(args):
"""
%prog fill gaps.bed bad.fasta
Perform gap filling of one assembly (bad) using sequences from another.
"""
p = OptionParser(fill.__doc__)
p.add_option("--extend", default=2000, type="int",
help="Extend seq flanking the gaps [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gapsbed, badfasta = args
Ext = opts.extend
gapdist = 2 * Ext + 1 # This is to prevent to replacement ranges intersect
gapsbed = mergeBed(gapsbed, d=gapdist, nms=True)
bed = Bed(gapsbed)
sizes = Sizes(badfasta).mapping
pf = gapsbed.rsplit(".", 1)[0]
extbed = pf + ".ext.bed"
fw = open(extbed, "w")
for b in bed:
gapname = b.accn
start, end = max(0, b.start - Ext - 1), b.start - 1
print("\t".join(str(x) for x in \
(b.seqid, start, end, gapname + "L")), file=fw)
start, end = b.end, min(sizes[b.seqid], b.end + Ext)
print("\t".join(str(x) for x in \
(b.seqid, start, end, gapname + "R")), file=fw)
fw.close()
fastaFromBed(extbed, badfasta, name=True) | [
"def",
"fill",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fill",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--extend\"",
",",
"default",
"=",
"2000",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Extend seq flanking the gaps [defa... | %prog fill gaps.bed bad.fasta
Perform gap filling of one assembly (bad) using sequences from another. | [
"%prog",
"fill",
"gaps",
".",
"bed",
"bad",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L637-L672 | train | 200,494 |
tanghaibao/jcvi | jcvi/assembly/patch.py | install | def install(args):
"""
%prog install patchers.bed patchers.fasta backbone.fasta alt.fasta
Install patches into backbone, using sequences from alternative assembly.
The patches sequences are generated via jcvi.assembly.patch.fill().
The output is a bedfile that can be converted to AGP using
jcvi.formats.agp.frombed().
"""
from jcvi.apps.align import blast
from jcvi.formats.fasta import SeqIO
p = OptionParser(install.__doc__)
p.set_rclip(rclip=1)
p.add_option("--maxsize", default=300000, type="int",
help="Maximum size of patchers to be replaced [default: %default]")
p.add_option("--prefix", help="Prefix of the new object [default: %default]")
p.add_option("--strict", default=False, action="store_true",
help="Only update if replacement has no gaps [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
pbed, pfasta, bbfasta, altfasta = args
maxsize = opts.maxsize # Max DNA size to replace gap
rclip = opts.rclip
blastfile = blast([altfasta, pfasta,"--wordsize=100", "--pctid=99"])
order = Bed(pbed).order
beforebed, afterbed = blast_to_twobeds(blastfile, order, rclip=rclip,
maxsize=maxsize)
beforefasta = fastaFromBed(beforebed, bbfasta, name=True, stranded=True)
afterfasta = fastaFromBed(afterbed, altfasta, name=True, stranded=True)
# Exclude the replacements that contain more Ns than before
ah = SeqIO.parse(beforefasta, "fasta")
bh = SeqIO.parse(afterfasta, "fasta")
count_Ns = lambda x: x.seq.count('n') + x.seq.count('N')
exclude = set()
for arec, brec in zip(ah, bh):
an = count_Ns(arec)
bn = count_Ns(brec)
if opts.strict:
if bn == 0:
continue
elif bn < an:
continue
id = arec.id
exclude.add(id)
logging.debug("Ignore {0} updates because of decreasing quality."\
.format(len(exclude)))
abed = Bed(beforebed, sorted=False)
bbed = Bed(afterbed, sorted=False)
abed = [x for x in abed if x.accn not in exclude]
bbed = [x for x in bbed if x.accn not in exclude]
abedfile = "before.filtered.bed"
bbedfile = "after.filtered.bed"
afbed = Bed()
afbed.extend(abed)
bfbed = Bed()
bfbed.extend(bbed)
afbed.print_to_file(abedfile)
bfbed.print_to_file(bbedfile)
shuffle_twobeds(afbed, bfbed, bbfasta, prefix=opts.prefix) | python | def install(args):
"""
%prog install patchers.bed patchers.fasta backbone.fasta alt.fasta
Install patches into backbone, using sequences from alternative assembly.
The patches sequences are generated via jcvi.assembly.patch.fill().
The output is a bedfile that can be converted to AGP using
jcvi.formats.agp.frombed().
"""
from jcvi.apps.align import blast
from jcvi.formats.fasta import SeqIO
p = OptionParser(install.__doc__)
p.set_rclip(rclip=1)
p.add_option("--maxsize", default=300000, type="int",
help="Maximum size of patchers to be replaced [default: %default]")
p.add_option("--prefix", help="Prefix of the new object [default: %default]")
p.add_option("--strict", default=False, action="store_true",
help="Only update if replacement has no gaps [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
pbed, pfasta, bbfasta, altfasta = args
maxsize = opts.maxsize # Max DNA size to replace gap
rclip = opts.rclip
blastfile = blast([altfasta, pfasta,"--wordsize=100", "--pctid=99"])
order = Bed(pbed).order
beforebed, afterbed = blast_to_twobeds(blastfile, order, rclip=rclip,
maxsize=maxsize)
beforefasta = fastaFromBed(beforebed, bbfasta, name=True, stranded=True)
afterfasta = fastaFromBed(afterbed, altfasta, name=True, stranded=True)
# Exclude the replacements that contain more Ns than before
ah = SeqIO.parse(beforefasta, "fasta")
bh = SeqIO.parse(afterfasta, "fasta")
count_Ns = lambda x: x.seq.count('n') + x.seq.count('N')
exclude = set()
for arec, brec in zip(ah, bh):
an = count_Ns(arec)
bn = count_Ns(brec)
if opts.strict:
if bn == 0:
continue
elif bn < an:
continue
id = arec.id
exclude.add(id)
logging.debug("Ignore {0} updates because of decreasing quality."\
.format(len(exclude)))
abed = Bed(beforebed, sorted=False)
bbed = Bed(afterbed, sorted=False)
abed = [x for x in abed if x.accn not in exclude]
bbed = [x for x in bbed if x.accn not in exclude]
abedfile = "before.filtered.bed"
bbedfile = "after.filtered.bed"
afbed = Bed()
afbed.extend(abed)
bfbed = Bed()
bfbed.extend(bbed)
afbed.print_to_file(abedfile)
bfbed.print_to_file(bbedfile)
shuffle_twobeds(afbed, bfbed, bbfasta, prefix=opts.prefix) | [
"def",
"install",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"align",
"import",
"blast",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"SeqIO",
"p",
"=",
"OptionParser",
"(",
"install",
".",
"__doc__",
")",
"p",
".",
"set_rclip"... | %prog install patchers.bed patchers.fasta backbone.fasta alt.fasta
Install patches into backbone, using sequences from alternative assembly.
The patches sequences are generated via jcvi.assembly.patch.fill().
The output is a bedfile that can be converted to AGP using
jcvi.formats.agp.frombed(). | [
"%prog",
"install",
"patchers",
".",
"bed",
"patchers",
".",
"fasta",
"backbone",
".",
"fasta",
"alt",
".",
"fasta"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L836-L910 | train | 200,495 |
tanghaibao/jcvi | jcvi/assembly/patch.py | refine | def refine(args):
"""
%prog refine breakpoints.bed gaps.bed
Find gaps within or near breakpoint region.
For breakpoint regions with no gaps, there are two options:
- Break in the middle of the region
- Break at the closest gap (--closest)
"""
p = OptionParser(refine.__doc__)
p.add_option("--closest", default=False, action="store_true",
help="In case of no gaps, use closest [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
breakpointsbed, gapsbed = args
ncols = len(open(breakpointsbed).next().split())
logging.debug("File {0} contains {1} columns.".format(breakpointsbed, ncols))
cmd = "intersectBed -wao -a {0} -b {1}".format(breakpointsbed, gapsbed)
pf = "{0}.{1}".format(breakpointsbed.split(".")[0], gapsbed.split(".")[0])
ingapsbed = pf + ".bed"
sh(cmd, outfile=ingapsbed)
fp = open(ingapsbed)
data = [x.split() for x in fp]
nogapsbed = pf + ".nogaps.bed"
largestgapsbed = pf + ".largestgaps.bed"
nogapsfw = open(nogapsbed, "w")
largestgapsfw = open(largestgapsbed, "w")
for b, gaps in groupby(data, key=lambda x: x[:ncols]):
gaps = list(gaps)
gap = gaps[0]
if len(gaps) == 1 and gap[-1] == "0":
assert gap[-3] == "."
print("\t".join(b), file=nogapsfw)
continue
gaps = [(int(x[-1]), x) for x in gaps]
maxgap = max(gaps)[1]
print("\t".join(maxgap), file=largestgapsfw)
nogapsfw.close()
largestgapsfw.close()
beds = [largestgapsbed]
toclean = [nogapsbed, largestgapsbed]
if opts.closest:
closestgapsbed = pf + ".closestgaps.bed"
cmd = "closestBed -a {0} -b {1} -d".format(nogapsbed, gapsbed)
sh(cmd, outfile=closestgapsbed)
beds += [closestgapsbed]
toclean += [closestgapsbed]
else:
pointbed = pf + ".point.bed"
pbed = Bed()
bed = Bed(nogapsbed)
for b in bed:
pos = (b.start + b.end) / 2
b.start, b.end = pos, pos
pbed.append(b)
pbed.print_to_file(pointbed)
beds += [pointbed]
toclean += [pointbed]
refinedbed = pf + ".refined.bed"
FileMerger(beds, outfile=refinedbed).merge()
# Clean-up
FileShredder(toclean)
return refinedbed | python | def refine(args):
"""
%prog refine breakpoints.bed gaps.bed
Find gaps within or near breakpoint region.
For breakpoint regions with no gaps, there are two options:
- Break in the middle of the region
- Break at the closest gap (--closest)
"""
p = OptionParser(refine.__doc__)
p.add_option("--closest", default=False, action="store_true",
help="In case of no gaps, use closest [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
breakpointsbed, gapsbed = args
ncols = len(open(breakpointsbed).next().split())
logging.debug("File {0} contains {1} columns.".format(breakpointsbed, ncols))
cmd = "intersectBed -wao -a {0} -b {1}".format(breakpointsbed, gapsbed)
pf = "{0}.{1}".format(breakpointsbed.split(".")[0], gapsbed.split(".")[0])
ingapsbed = pf + ".bed"
sh(cmd, outfile=ingapsbed)
fp = open(ingapsbed)
data = [x.split() for x in fp]
nogapsbed = pf + ".nogaps.bed"
largestgapsbed = pf + ".largestgaps.bed"
nogapsfw = open(nogapsbed, "w")
largestgapsfw = open(largestgapsbed, "w")
for b, gaps in groupby(data, key=lambda x: x[:ncols]):
gaps = list(gaps)
gap = gaps[0]
if len(gaps) == 1 and gap[-1] == "0":
assert gap[-3] == "."
print("\t".join(b), file=nogapsfw)
continue
gaps = [(int(x[-1]), x) for x in gaps]
maxgap = max(gaps)[1]
print("\t".join(maxgap), file=largestgapsfw)
nogapsfw.close()
largestgapsfw.close()
beds = [largestgapsbed]
toclean = [nogapsbed, largestgapsbed]
if opts.closest:
closestgapsbed = pf + ".closestgaps.bed"
cmd = "closestBed -a {0} -b {1} -d".format(nogapsbed, gapsbed)
sh(cmd, outfile=closestgapsbed)
beds += [closestgapsbed]
toclean += [closestgapsbed]
else:
pointbed = pf + ".point.bed"
pbed = Bed()
bed = Bed(nogapsbed)
for b in bed:
pos = (b.start + b.end) / 2
b.start, b.end = pos, pos
pbed.append(b)
pbed.print_to_file(pointbed)
beds += [pointbed]
toclean += [pointbed]
refinedbed = pf + ".refined.bed"
FileMerger(beds, outfile=refinedbed).merge()
# Clean-up
FileShredder(toclean)
return refinedbed | [
"def",
"refine",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"refine",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--closest\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"In case of no gaps,... | %prog refine breakpoints.bed gaps.bed
Find gaps within or near breakpoint region.
For breakpoint regions with no gaps, there are two options:
- Break in the middle of the region
- Break at the closest gap (--closest) | [
"%prog",
"refine",
"breakpoints",
".",
"bed",
"gaps",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L913-L988 | train | 200,496 |
tanghaibao/jcvi | jcvi/assembly/patch.py | patcher | def patcher(args):
"""
%prog patcher backbone.bed other.bed
Given optical map alignment, prepare the patchers. Use --backbone to suggest
which assembly is the major one, and the patchers will be extracted from
another assembly.
"""
from jcvi.formats.bed import uniq
p = OptionParser(patcher.__doc__)
p.add_option("--backbone", default="OM",
help="Prefix of the backbone assembly [default: %default]")
p.add_option("--object", default="object",
help="New object name [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
backbonebed, otherbed = args
backbonebed = uniq([backbonebed])
otherbed = uniq([otherbed])
pf = backbonebed.split(".")[0]
key = lambda x: (x.seqid, x.start, x.end)
# Make a uniq bed keeping backbone at redundant intervals
cmd = "intersectBed -v -wa"
cmd += " -a {0} -b {1}".format(otherbed, backbonebed)
outfile = otherbed.rsplit(".", 1)[0] + ".not." + backbonebed
sh(cmd, outfile=outfile)
uniqbed = Bed()
uniqbedfile = pf + ".merged.bed"
uniqbed.extend(Bed(backbonebed))
uniqbed.extend(Bed(outfile))
uniqbed.print_to_file(uniqbedfile, sorted=True)
# Condense adjacent intervals, allow some chaining
bed = uniqbed
key = lambda x: range_parse(x.accn).seqid
bed_fn = pf + ".patchers.bed"
bed_fw = open(bed_fn, "w")
for k, sb in groupby(bed, key=key):
sb = list(sb)
chr, start, end, strand = merge_ranges(sb)
print("\t".join(str(x) for x in \
(chr, start, end, opts.object, 1000, strand)), file=bed_fw)
bed_fw.close() | python | def patcher(args):
"""
%prog patcher backbone.bed other.bed
Given optical map alignment, prepare the patchers. Use --backbone to suggest
which assembly is the major one, and the patchers will be extracted from
another assembly.
"""
from jcvi.formats.bed import uniq
p = OptionParser(patcher.__doc__)
p.add_option("--backbone", default="OM",
help="Prefix of the backbone assembly [default: %default]")
p.add_option("--object", default="object",
help="New object name [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
backbonebed, otherbed = args
backbonebed = uniq([backbonebed])
otherbed = uniq([otherbed])
pf = backbonebed.split(".")[0]
key = lambda x: (x.seqid, x.start, x.end)
# Make a uniq bed keeping backbone at redundant intervals
cmd = "intersectBed -v -wa"
cmd += " -a {0} -b {1}".format(otherbed, backbonebed)
outfile = otherbed.rsplit(".", 1)[0] + ".not." + backbonebed
sh(cmd, outfile=outfile)
uniqbed = Bed()
uniqbedfile = pf + ".merged.bed"
uniqbed.extend(Bed(backbonebed))
uniqbed.extend(Bed(outfile))
uniqbed.print_to_file(uniqbedfile, sorted=True)
# Condense adjacent intervals, allow some chaining
bed = uniqbed
key = lambda x: range_parse(x.accn).seqid
bed_fn = pf + ".patchers.bed"
bed_fw = open(bed_fn, "w")
for k, sb in groupby(bed, key=key):
sb = list(sb)
chr, start, end, strand = merge_ranges(sb)
print("\t".join(str(x) for x in \
(chr, start, end, opts.object, 1000, strand)), file=bed_fw)
bed_fw.close() | [
"def",
"patcher",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"uniq",
"p",
"=",
"OptionParser",
"(",
"patcher",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--backbone\"",
",",
"default",
"=",
"\"OM\"",
",",
"he... | %prog patcher backbone.bed other.bed
Given optical map alignment, prepare the patchers. Use --backbone to suggest
which assembly is the major one, and the patchers will be extracted from
another assembly. | [
"%prog",
"patcher",
"backbone",
".",
"bed",
"other",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/patch.py#L1012-L1065 | train | 200,497 |
tanghaibao/jcvi | jcvi/variation/str.py | treds | def treds(args):
"""
%prog treds hli.tred.tsv
Compile allele_frequency for TREDs results. Write data.tsv, meta.tsv and
mask.tsv in one go.
"""
p = OptionParser(treds.__doc__)
p.add_option("--csv", default=False, action="store_true",
help="Also write `meta.csv`")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
tredresults, = args
df = pd.read_csv(tredresults, sep="\t")
tredsfile = datafile("TREDs.meta.csv")
tf = pd.read_csv(tredsfile)
tds = list(tf["abbreviation"])
ids = list(tf["id"])
tags = ["SampleKey"]
final_columns = ["SampleKey"]
afs = []
for td, id in zip(tds, ids):
tag1 = "{}.1".format(td)
tag2 = "{}.2".format(td)
if tag2 not in df:
afs.append("{}")
continue
tags.append(tag2)
final_columns.append(id)
a = np.array(list(df[tag1]) + list(df[tag2]))
counts = alleles_to_counts(a)
af = counts_to_af(counts)
afs.append(af)
tf["allele_frequency"] = afs
metafile = "TREDs_{}_SEARCH.meta.tsv".format(timestamp())
tf.to_csv(metafile, sep="\t", index=False)
logging.debug("File `{}` written.".format(metafile))
if opts.csv:
metacsvfile = metafile.rsplit(".", 1)[0] + ".csv"
tf.to_csv(metacsvfile, index=False)
logging.debug("File `{}` written.".format(metacsvfile))
pp = df[tags]
pp.columns = final_columns
datafile = "TREDs_{}_SEARCH.data.tsv".format(timestamp())
pp.to_csv(datafile, sep="\t", index=False)
logging.debug("File `{}` written.".format(datafile))
mask([datafile, metafile]) | python | def treds(args):
"""
%prog treds hli.tred.tsv
Compile allele_frequency for TREDs results. Write data.tsv, meta.tsv and
mask.tsv in one go.
"""
p = OptionParser(treds.__doc__)
p.add_option("--csv", default=False, action="store_true",
help="Also write `meta.csv`")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
tredresults, = args
df = pd.read_csv(tredresults, sep="\t")
tredsfile = datafile("TREDs.meta.csv")
tf = pd.read_csv(tredsfile)
tds = list(tf["abbreviation"])
ids = list(tf["id"])
tags = ["SampleKey"]
final_columns = ["SampleKey"]
afs = []
for td, id in zip(tds, ids):
tag1 = "{}.1".format(td)
tag2 = "{}.2".format(td)
if tag2 not in df:
afs.append("{}")
continue
tags.append(tag2)
final_columns.append(id)
a = np.array(list(df[tag1]) + list(df[tag2]))
counts = alleles_to_counts(a)
af = counts_to_af(counts)
afs.append(af)
tf["allele_frequency"] = afs
metafile = "TREDs_{}_SEARCH.meta.tsv".format(timestamp())
tf.to_csv(metafile, sep="\t", index=False)
logging.debug("File `{}` written.".format(metafile))
if opts.csv:
metacsvfile = metafile.rsplit(".", 1)[0] + ".csv"
tf.to_csv(metacsvfile, index=False)
logging.debug("File `{}` written.".format(metacsvfile))
pp = df[tags]
pp.columns = final_columns
datafile = "TREDs_{}_SEARCH.data.tsv".format(timestamp())
pp.to_csv(datafile, sep="\t", index=False)
logging.debug("File `{}` written.".format(datafile))
mask([datafile, metafile]) | [
"def",
"treds",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"treds",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--csv\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Also write `meta.csv`\"",... | %prog treds hli.tred.tsv
Compile allele_frequency for TREDs results. Write data.tsv, meta.tsv and
mask.tsv in one go. | [
"%prog",
"treds",
"hli",
".",
"tred",
".",
"tsv"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L350-L405 | train | 200,498 |
tanghaibao/jcvi | jcvi/variation/str.py | stutter | def stutter(args):
"""
%prog stutter a.vcf.gz
Extract info from lobSTR vcf file. Generates a file that has the following
fields:
CHR, POS, MOTIF, RL, ALLREADS, Q
"""
p = OptionParser(stutter.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
vcf, = args
pf = op.basename(vcf).split(".")[0]
execid, sampleid = pf.split("_")
C = "vcftools --remove-filtered-all --min-meanDP 10"
C += " --gzvcf {} --out {}".format(vcf, pf)
C += " --indv {}".format(sampleid)
info = pf + ".INFO"
if need_update(vcf, info):
cmd = C + " --get-INFO MOTIF --get-INFO RL"
sh(cmd)
allreads = pf + ".ALLREADS.FORMAT"
if need_update(vcf, allreads):
cmd = C + " --extract-FORMAT-info ALLREADS"
sh(cmd)
q = pf + ".Q.FORMAT"
if need_update(vcf, q):
cmd = C + " --extract-FORMAT-info Q"
sh(cmd)
outfile = pf + ".STUTTER"
if need_update((info, allreads, q), outfile):
cmd = "cut -f1,2,5,6 {}".format(info)
cmd += r" | sed -e 's/\t/_/g'"
cmd += " | paste - {} {}".format(allreads, q)
cmd += " | cut -f1,4,7"
sh(cmd, outfile=outfile) | python | def stutter(args):
"""
%prog stutter a.vcf.gz
Extract info from lobSTR vcf file. Generates a file that has the following
fields:
CHR, POS, MOTIF, RL, ALLREADS, Q
"""
p = OptionParser(stutter.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
vcf, = args
pf = op.basename(vcf).split(".")[0]
execid, sampleid = pf.split("_")
C = "vcftools --remove-filtered-all --min-meanDP 10"
C += " --gzvcf {} --out {}".format(vcf, pf)
C += " --indv {}".format(sampleid)
info = pf + ".INFO"
if need_update(vcf, info):
cmd = C + " --get-INFO MOTIF --get-INFO RL"
sh(cmd)
allreads = pf + ".ALLREADS.FORMAT"
if need_update(vcf, allreads):
cmd = C + " --extract-FORMAT-info ALLREADS"
sh(cmd)
q = pf + ".Q.FORMAT"
if need_update(vcf, q):
cmd = C + " --extract-FORMAT-info Q"
sh(cmd)
outfile = pf + ".STUTTER"
if need_update((info, allreads, q), outfile):
cmd = "cut -f1,2,5,6 {}".format(info)
cmd += r" | sed -e 's/\t/_/g'"
cmd += " | paste - {} {}".format(allreads, q)
cmd += " | cut -f1,4,7"
sh(cmd, outfile=outfile) | [
"def",
"stutter",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"stutter",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog stutter a.vcf.gz
Extract info from lobSTR vcf file. Generates a file that has the following
fields:
CHR, POS, MOTIF, RL, ALLREADS, Q | [
"%prog",
"stutter",
"a",
".",
"vcf",
".",
"gz"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L408-L452 | train | 200,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.